如何在C++中使用带自定义构造函数的类作为map的值类型
问题原因
你代码报错的核心原因是std::map的operator[]的特殊逻辑:当你访问的key不存在于map中时,这个运算符会自动默认构造一个对应值类型的对象,将其和key绑定后插入map,再返回这个对象的引用。而你给testclass加了带参数的自定义构造函数之后,编译器就不会自动生成无参的默认构造函数了,自然无法完成默认构造的步骤,所以编译失败。
解决方案1:使用无需默认构造的插入接口(推荐,不需要修改类定义)
你可以用insert、emplace这类接口插入元素,这些接口不需要值类型支持默认构造。
示例代码(用emplace,C++11及以上支持,性能最优)
#include <iostream> #include <map> using namespace std; class testclass { public: int x = 1; testclass(int arg) { x = arg; } }; int main() { map<int,testclass> thismap; // 直接原地构造testclass对象插入map auto [it, insert_success] = thismap.emplace(2, testclass(5)); // 拿到插入后对象的引用 testclass& x = it->second; cout << x.x << endl; // 输出5 return 0; }
如果你的编译器不支持C++17的结构化绑定,也可以这么写:
pair<map<int,testclass>::iterator, bool> res = thismap.emplace(2, testclass(5)); testclass& x = res.first->second;
用insert的写法示例:
thismap.insert(make_pair(2, testclass(5))); testclass& x = thismap.at(2); // 用at访问已存在的key,不会触发默认构造
解决方案2:给类补充默认构造能力
如果你确实需要用到operator[]的便捷性,可以给类加上无参默认构造,或者给构造函数的参数加默认值:
示例代码:
class testclass { public: int x = 1; // 给参数加默认值,既支持带参构造,也支持无参默认构造 testclass(int arg = 1) { x = arg; } }; int main() { map<int,testclass> thismap; // 现在operator[]可以正常使用了,不存在的key会用默认构造生成x=1的对象 testclass &x = thismap[2]; cout << x.x << endl; // 输出1 return 0; }
内容的提问来源于stack exchange,提问作者jujumumu
相关产品推荐
相关产品推荐

