求助:C++代码报错NO MATCHING FUNCTION FOR CALL TO 'PERSON::PERSON()'
问题分析与解决
错误原因
你遇到的NO MATCHING FUNCTION FOR CALL TO 'PERSON::PERSON()'错误,核心原因是Person类只定义了带参数的构造函数,C++编译器会自动取消默认生成的无参构造函数。而代码中Person people[numPeople];这行创建Person数组时,会尝试调用每个元素的无参构造函数初始化,但你的类里没有这个构造函数,因此编译报错。
此外代码还有两个隐性问题:
- 调用
sqrt和pow数学函数时,未包含<cmath>头文件,可能引发未定义行为; const int numInfected = numPeople * 0.1;中浮点数转整数会发生截断,若numPeople不是10的倍数,结果会不符合预期。
修复方案
方案1:添加无参构造函数
在Person类中补充无参构造函数,给成员变量设置默认值:
Person() : id(0), x(0), y(0), infected(false) {}
方案2:改用std::vector动态创建对象(更推荐)
避免数组初始化依赖无参构造的限制,用vector存储Person对象,直接构造添加元素。
完整修复后的代码
#include <iostream> #include <cmath> // 新增:包含数学函数头文件 #include <vector> // 新增:使用vector存储对象 class Person { public: Person(int _id, int _x, int _y, bool _infected) : id(_id), x(_x), y(_y), infected(_infected) {} int id; int x; int y; bool infected; }; void display(const std::vector<Person>& people) { system("cls"); for (size_t i = 0; i < people.size(); ++i) { std::cout << "Person " << people[i].id << ": "; std::cout << "位置 (" << people[i].x << ", " << people[i].y << ")"; std::cout << " - 是否感染: " << (people[i].infected ? "是" : "否") << std::endl; } } int main() { srand(time(nullptr)); const int numPeople = 100; // 优化:明确浮点数转整数的行为 const int numInfected = static_cast<int>(numPeople * 0.1); const int n = 7; // 改用vector,直接构造对象添加,无需无参构造 std::vector<Person> people; people.reserve(numPeople); // 预分配空间提升性能 for (int i = 0; i < numPeople; ++i) { int x = rand() % 201 - 100; int y = rand() % 201 - 100; bool infected = i < numInfected; people.emplace_back(i + 1, x, y, infected); // 直接在vector内存中构造对象 } for (int day = 1; day <= n; ++day) { for (size_t i = 0; i < people.size(); ++i) { if (!people[i].infected) { int dx = rand() % 3 - 1; int dy = rand() % 3 - 1; people[i].x += dx; people[i].y += dy; } } for (size_t i = 0; i < people.size(); ++i) { if (people[i].infected) { for (size_t j = 0; j < people.size(); ++j) { if (!people[j].infected) { double distance = sqrt(pow(people[i].x - people[j].x, 2) + pow(people[i].y - people[j].y, 2)); if (distance <= sqrt(2)) { if (rand() % 100 < 90) { people[j].infected = true; } } } } } } display(people); } int numInfectedAtEnd = 0; for (const auto& p : people) { if (p.infected) { numInfectedAtEnd++; } } std::cout << "最终感染人数: " << numInfectedAtEnd << std::endl; return 0; }
额外说明
- 改用
std::vector后,无需依赖无参构造函数,代码更灵活,还能避免数组大小必须是编译期常量的限制; emplace_back直接在vector内存中构造对象,减少一次拷贝操作,性能更优;- 用
size_t类型遍历vector,避免int与size_t的类型不匹配警告。
内容的提问来源于stack exchange,提问作者irazff
相关产品推荐
相关产品推荐

