![7108f20dbe9a8f625ae565aaf8d4bd1f.png](https://img-blog.csdnimg.cn/img_convert/7108f20dbe9a8f625ae565aaf8d4bd1f.png)
今天写了一个简单的小程序:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class student
{
public:
string name;
int age;
student(string n, int a)
{
this->name = n;
this->age = a;
}
};
int main()
{
map<int, student> mp;
mp[1] = student("jack", 25);
mp[2] = student("kate", 25);
cout << mp[1].name << endl;
return 0;
}
看起来没有问题,但是运行时报错:
test.cpp:23:6: required from here
/usr/include/c++/4.8.2/bits/stl_map.h:469:59: 错误:对‘student::student()’的调用没有匹配的函数
__i = insert(__i, value_type(__k, mapped_type()));
^
/usr/include/c++/4.8.2/bits/stl_map.h:469:59: 附注:备选是:
test.cpp:12:3: 附注:student::student(std::string, int)
student(string n, int a)
^
test.cpp:12:3: 附注: 备选需要 2 实参,但提供了 0 个
test.cpp:6:7: 附注:student::student(const student&)
class student
^
test.cpp:6:7: 附注: 备选需要 1 实参,但提供了 0 个
问了一下同事 aiden,发现问题在于map在编译阶段发现mp[1]所对应的value不存在,会调用默认构造函数构造一个student对象,可是class student已经写了构造函数,编译器不会生成默认构造函数,所以报错显示:对‘student::student()’的调用没有匹配的函数。
解决方案:添加默认构造函数
class student
{
public:
string name;
int age;
student(string n, int a)
{
this->name = n;
this->age = a;
}
student(){}
};