赋值运算符重载¶
参考:Assignment
规范¶
赋值运算符(operator=
)是二元运算符,除了遵循二元运算符的规范外,还有以下限制:
- 必须是非静态成员函数
- 无法被派生类继承
- 如果不存在,默认的
opeator=
函数会被编译器生成
赋值 vs. 复制¶
赋值(copy assignment
)运算和复制(copy
)操作有区别,后者在新对象构造期间调用
// Copy constructor is called--not overloaded copy assignment operator!
Point pt3 = pt1;
// The previous initialization is similar to the following:
Point pt4(pt1); // Copy constructor call.
最佳实践:定义赋值运算的同时定义复制构造器和析构器
示例¶
定义类Point
,重载赋值运算符,重载复制构造器和析构器
class Point {
public:
Point(int x, int y) : _x{x}, _y{y} {}
Point() : _x(0), _y(0) {}
Point(const Point &point) : _x{point._x}, _y{point._y} {}
// Right side of copy assignment is the argument.
Point &operator=(const Point &);
inline void print() {
cout << "x = " << _x << " y = " << _y << endl;
}
private:
int _x, _y;
};
// Define copy assignment operator.
Point &Point::operator=(const Point &otherPoint) {
_x = otherPoint._x;
_y = otherPoint._y;
// Assignment operator returns left side of assignment.
return *this;
}
int main() {
Point pt1{2, 3}, pt2{3, 5};
// 使用复制构造器
Point pt3(pt2);
pt3.print();
// 使用赋值运算符
pt1 = pt2;
pt1.print();
}