【发布时间】:2016-02-03 23:27:55
【问题描述】:
struct MyStruct {
const int a, b;
MyStruct(int a, int b): a(a), b(b) {}
}
map<int, MyStruct> m;
m[2] = MyStruct(3, 4); // this would fail. Of course I can use m.insert( .... )
MyStruct t = m[2]; // this would not compile, because there is no assignment operator.
我会得到以下编译错误。
[assignment operator] is implicitly deleted because the default definition would be ill-formed:
如何解决这个问题?我希望有恒定的成员变量,以避免将来意外修改
【问题讨论】:
-
MyStruct t = m[2];应该使用复制构造函数而不是赋值运算符。这被称为copy initialization -
您可以做的不是将成员变量设为 const,而是将它们设为私有。然后具有访问它们的功能。并且没有允许它们被更新的功能。
-
您的问题不清楚。您显示的错误消息来自
m[2] = MyStruct(3,4);行。但是,您已经正确地注意到该行失败,并且您还正确地注意到您可以改用m.insert。MyStruct t = m[2];行是一个错误,但原因完全不同,与 const 变量无关 -
operator[]不能与映射类型没有默认构造函数的映射一起使用,因为如果不存在,它需要创建一个新条目。您必须使用m.find查找此地图。
标签: c++ return-value assignment-operator