赋值运算符不工作

assignment operator not working

本文关键字:工作 赋值运算符      更新时间:2023-10-16

这个代码是什么:

MyClass t;
t = MyClass(100); 

我在代码中使用了类似的东西,我得到了编译错误error: no match for ‘operator=’。我把它理解成Java语言,但显然不同。

我有这样声明的分配运算符:

MyClass& operator=(Myclass& other)

当我把代码改成这样时,它就起作用了:

MyClass temp(100);
t = temp;

我不能这样做:

Myclass t(100)

您需要将rhs声明为const-reference

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

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

这是因为在分配时

t = MyClass(100);

赋值右侧的对象是临时对象,并且不能引用临时对象。然而,您可以有一个常量引用,因此如果您定义像这样的赋值运算符

MyClass& operator=(const Myclass& other)

它会起作用的。

如果你使用新的C++11右值参考:,它也会起作用

MyClass& operator=(Myclass&& other)

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

MyClass;运算符=(const Myclass&other);