C++报错:No matching constructor for initialization of 'Person'求助
问题修复方案
错误原因
你给Person类定义了带参数的构造函数后,C++编译器不会自动生成无参的默认构造函数,所以Person person;这行代码试图创建无参对象时,找不到匹配的构造函数,触发了No matching constructor for initialization of 'Person'错误。
另外你循环里的person.show()逻辑不对,这个空对象没有有效数据,你应该直接遍历vector里的每个Person实例来调用show方法。
修复后的代码
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; class Person { public: string name; int age; Person(string name, int age) { this->name = move(name); this->age = age; } void show() { cout << name << " : " << age << endl; } // 补全sortName静态比较函数的实现 static bool sortName(const Person& a, const Person& b) { return a.name < b.name; } }; // 补全mySort函数的逻辑 void mySort(vector<Person>* people, bool (*compare)(const Person&, const Person&)) { sort(people->begin(), people->end(), compare); } int main() { vector<Person> list = { Person("Smith", 20), Person("Andrew", 31), Person("Beck", 19) }; // 移除错误的无参对象定义 mySort(&list, Person::sortName); // 修正参数:传递函数指针而非调用函数,变量名改为list for (auto& value : list) { // 使用引用避免不必要的拷贝 value.show(); // 直接调用当前遍历对象的show方法 } return 0; }
额外说明
- 移除了无用的
Person person;定义,彻底解决构造函数匹配错误。 - 修正
mySort调用的参数:把错误的people改为实际的vector变量名list,同时将Person::sortName()改为Person::sortName——这里需要传递的是函数指针,而非调用函数的返回值。 - 循环中通过
auto& value遍历容器,直接调用value.show()打印每个人员的姓名和年龄,这才是符合需求的正确逻辑。 - 补全了
sortName静态函数和mySort函数的实现,确保代码可以正常编译运行。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

