C ++返回一个具有常量成员变量的对象 - 隐式删除赋值运算符

时间:2015-11-03 17:25:12

标签: c++ return-value assignment-operator

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:

如何解决这个问题?我想拥有常量成员变量以避免将来意外修改

1 个答案:

答案 0 :(得分:0)

有一个自动生成的复制构造函数,它等同于

MyStruct(MyStruct &s): a(s.a), b(s.b) {}

用它来创建副本:

MyStruct t(m[2]);