赋值运算符不工作
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)
您需要将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);
相关文章:
- 重载Singly Linked List中的赋值运算符
- 使用赋值运算符重载从类中返回jobject
- 标准库类型的赋值运算符的引用限定符
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 基类和派生类的多态赋值运算符
- 为用户定义的类正确调用复制构造函数/赋值运算符
- CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc
- 为什么初始化时没有调用重载赋值运算符?
- 赋值运算符重载和自赋值
- 为什么我的类工作正常,即使在返回垃圾值作为赋值运算符和空复制构造函数的返回之后
- 有人可以解释速记赋值运算符的实际工作原理吗?
- 使赋值运算符在声明上工作
- std::string 赋值运算符如何工作
- 赋值运算符不工作
- 复制构造函数未被调用,无法理解赋值运算符的工作方式
- std::swap在构造函数、赋值运算符和析构函数方面是如何工作的
- 在本例中,赋值运算符重载解析是如何工作的?结果出乎我意料
- 我能让赋值运算符像复制构造函数一样工作吗