【发布时间】:2019-10-18 08:21:00
【问题描述】:
具有“const int&”数据成员的类在重载 operator=(编译器为 g++)时会导致以下编译错误:
分配只读位置。
把数据成员改成'const int*'就可以了。
为什么?
#include <iostream>
using namespace std;
class B {
private:
const int& ir;
//const int* ir;
public:
B(const int& i) : ir(i) {}
//B(const int& i) : ir(&i) {}
B& operator=(B& b) { ir = b.ir; return *this; }
};
g++ 错误信息:
opertostack.cpp:9:31: error: assignment of read-only location ‘((B*)this)-> B::ir’
B& operator=(B& b) { ir = b.ir; return *this; }
^~
【问题讨论】:
-
你知道指针和引用的区别吗?
-
您不能分配给 const 引用。而且您几乎肯定不希望将引用作为成员变量(const 或其他)。
-
'ir' 可以正常重新分配。它是一个常量 &。我错过了什么吗?
-
@Jack 它不能“正常重新分配” - 这就是错误消息告诉你的内容。
-
所有变量“只能初始化一次”——你需要弄清楚初始化和赋值之间的区别——这在 C++ 中非常重要。
标签: c++