std::map 操作符[] 编译提示 error C2512: 自定义类型 没有合适的默认构造函数可用

原因:map的value没有定义默认构造函数

class myType
{
public:
myType(){a=10000;}  //没有定义默认构造函数,std::map的operator[]将会编译报错
myType(int a){this->a = a;}
int a;
}
...
std::map<int, myType> myMap;
myMap.insert(pair<int myType>(0,myType(1)));
myMap.insert(pair<int myType>(1,myType(2)));
int a = myMap[0].a;  //operator [] 获得key为0对应的value,此时a=1
myMap[2] = myType(3); //operator [] 往map插入新的元素,key为2,对应的value通过构造函数myType(int a)得到,a=3
int a = myMap[3].a;  //operator [] 往map插入新的元素,key为3,对应的value通过构造函数myType()得到,a=10000

见std::map operator [] 说明:http://www.cplusplus.com/reference/map/map/operator[]/

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

你可能感兴趣的:(C/C++)