我正在设计一个类,它应该有一个名为K. 我也希望这个类有一个复制赋值运算符,但编译器似乎从任何具有 const 数据成员的类中隐式删除了复制赋值运算符。这段代码说明了基本问题:
class A
{
private:
const int K;
public:
A(int k) : K(k) {} // constructor
A() = delete; // delete default constructor, since we have to set K at initialization
A & operator=(A const & in) { K = in.K; } // copy assignment operator that generates the error below
}
Run Code Online (Sandbox Code Playgroud)
这是它生成的错误:
constructor.cpp:13:35: error: cannot assign to non-static data member 'K' with const-
qualified type 'const int'
A & operator=(A const & in) { …Run Code Online (Sandbox Code Playgroud)