我收到错误:
error: no matching function for call to 'A::A()' note: candidates are: A::A(const A&) note: A::A(const std::string&,size_t)
由此:
#include <map>
#include <string>
using std::map;
using std::string;
class A {
public:
string path;
size_t size;
A (const string& p,size_t s) : path(p),size(s) { }
A (const A& f) : path(f.path),size(f.size) { }
A& operator=(const A& rhs) {
path = rhs.path;
size = rhs.size;
return *this;
}
};
int main(int argc,char **argv)
{
map<string,A> mymap;
A a("world",1);
mymap["hello"] = a; // <----- here
A b(mymap["hello"]); // <----- and here
}
请告诉我为什么代码想要一个没有参数的构造函数.
解决方法
mymap [“hello”]可以尝试创建一个值初始化的A,因此需要一个默认的构造函数.
如果您使用类型T作为映射值(并计划通过operator []访问值),则它需要是默认构造的 – 即您需要一个无参数(默认)构造函数.如果找不到提供密钥的值,则地图上的operator []将对映射值进行值初始化.