任务

严格地说,赋值运算符 (=) 是二元运算符。 其声明与任何其他二元运算符的相同,但有以下例外:

  • 它必须是非静态成员函数。 没有“operator=”可声明为非成员函数
  • 它不由派生类继承。
  • 默认“operator=”函数可由类类型的编译器生成(如果该函数不存在)

以下示例阐释如何声明赋值运算符:

class Point
{
public:
    int _x, _y;

    // Right side of copy assignment is the argument.
    Point& operator=(const Point&);
};

// 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, pt2;
    pt1 = pt2;
}

所提供的自变量是表达式的右侧。 此运算符返回对象以保留赋值运算符的行为,赋值运算符在赋值完成后返回左侧的值。 这样能形成赋值链,例如:

pt1 = pt2 = pt3;

复制赋值运算符不会与复制构造函数混淆。 后者是在从现有对象构造新对象的过程中调用的:

// 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.

注意

建议遵循三法则 (Rule of Three),即定义复制赋值运算符的类还应显式定义复制构造函数和析构函数,以及移动构造函数和移动赋值运算符(从 C++11 开始)。

另请参阅