隐式赋值运算符
implicit assignment operators
本文关键字:赋值运算符 更新时间:2023-10-16
如果我的类上有运算符重载,运算符的赋值版本是否也隐式创建?
class square{
square operator+(const square& B);
void operator=(const square& B);
};
如在,我可以打电话吗
square A, B;
A += B;
编译器隐式决定调用operator+
然后operator=
?
不,+=
必须显式定义。
作为旁注,operator+
通常应该创建一个新对象:
square operator+(const square& B);
operator=
应该返回对*this
的引用:
square& operator=(const square& B);
还值得注意的是,operator+
通常是根据operator+=
来实现的,即 operator+
调用operator+=
新副本。
不,运算符不是隐式定义的。但是,boost/operators.hpp
定义了有用的帮助程序模板,以避免使用样板代码。他们文档中的示例:
例如,如果您声明一个类似这样的类:
class MyInt
: boost::operators<MyInt> {
bool operator<(const MyInt& x) const;
bool operator==(const MyInt& x) const;
MyInt& operator+=(const MyInt& x);
MyInt& operator-=(const MyInt& x);
MyInt& operator*=(const MyInt& x);
MyInt& operator/=(const MyInt& x);
MyInt& operator%=(const MyInt& x);
MyInt& operator|=(const MyInt& x);
MyInt& operator&=(const MyInt& x);
MyInt& operator^=(const MyInt& x);
MyInt& operator++();
MyInt& operator--(); };
然后
operators<>
模板添加了十几个额外的运算符,例如operator>
、<=
、>=
和 (二进制)+
.模板的双参数形式也提供给 允许与其他类型交互。
此外,还支持使用算术运算符模板隐式"推断"一组特定的运算符。
No operator+=
是它自己的运算符,必须显式定义。
请注意,operator+
应返回一个新对象,而不是对原始对象的引用。原始对象应保持不变。
operator+=
应返回添加所需值的原始对象。 operator+=
通常更可取,因为它消除了临时对象。
相关文章:
- 重载Singly Linked List中的赋值运算符
- 使用赋值运算符重载从类中返回jobject
- 标准库类型的赋值运算符的引用限定符
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 基类和派生类的多态赋值运算符
- 为用户定义的类正确调用复制构造函数/赋值运算符
- CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc
- 为什么初始化时没有调用重载赋值运算符?
- 赋值运算符重载和自赋值
- C++矢量复制构造函数和赋值运算符是否也复制保留空间?
- Qt PL/SQL - 赋值运算符 - 字符串缓冲区太小
- 对 r 值使用移动赋值运算符时的异常
- 由于没有使用赋值运算符,映射的值是如何初始化的?
- 默认赋值运算符如何在实际 STL 中实现
- 使用赋值运算符复制 std::vector
- C++ 通过自定义赋值运算符隐式转换函数参数
- 赋值运算符的奇怪行为
- C++赋值运算符,我们可以用 copy 替换它吗?