gpt4 book ai didi

c++ - 赋值运算符不工作

转载 作者:太空宇宙 更新时间:2023-11-04 15:38:04 26 4
gpt4 key购买 nike

这段代码是做什么的:

MyClass t;
t = MyClass(100);

我在我的代码中使用了类似的东西,但我得到了编译错误 error: no match for ‘operator=’。我像在 Java 中一样解释它,但显然它是不同的。

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

MyClass& operator=(Myclass& other)

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

MyClass temp(100);
t = temp;

我不能这样做:

Myclass t(100)

最佳答案

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

MyClass& operator=(const Myclass& other);

当你有

t = MyClass(100);

右侧是临时对象,非 const 左值引用不能绑定(bind)到临时对象。

你后面的尝试

MyClass t2(100);
t = t2;

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

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

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

关于c++ - 赋值运算符不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com