赋值运算符不工作

assignment operator not working

这段代码是做什么的:

MyClass t;
t = MyClass(100); 

我在我的代码中使用了类似的东西,但出现编译错误 error: no match for ‘operator=’。我对它的解释与 Java 类似,但显然有所不同。

我有这样声明的赋值运算符:

MyClass& operator=(Myclass& other)

当我将我的代码更改为这个时,它起作用了:

MyClass temp(100);
t = temp;

我做不到:

Myclass t(100)

您的赋值运算符应将常量引用作为参数。因为临时 MyClass(100) 无法绑定到非常量引用,所以无法调用您当前的实现。

您需要将 rhs 声明为常量引用

MyClass& operator=(const Myclass& other);

当你有

t = MyClass(100);

右侧是临时对象,非常量左值引用不能绑定到临时对象。

你后面的尝试

MyClass t2(100);
t = t2;

创建命名对象 t2,因为这是一个实际的非常量左值,您的赋值运算符的参数可以绑定到它。

如果你尝试的话,你可以直接看到这个

MyClass& r1 = MyClass(100); // invalid, non-const ref to temporary
const MyClass& r2 = MyClass(100); // valid, const ref to temporary
MyClass mc(100);
MyClass& r3 = mc; // valid, non-const ref can bind to a named object
                  // as long as the object itself isn't declared const
const MyClass& r4 = mc; // valid, you can bind a non-const ref as well

那是因为在作业中

t = MyClass(100);

赋值右侧的对象是临时对象,不能引用临时对象。但是,您可以有一个 constant 引用,因此如果您将赋值运算符定义为

MyClass& operator=(const Myclass& other)

它会起作用。

如果您使用新的 C++11 右值引用,它也可以工作:

MyClass& operator=(Myclass&& other)

忘记常量 C++ 编译器应在右侧绑定 const 对象

MyClass& operator=(const Myclass& other);