LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 147|回复: 0

任务

[复制链接]
发表于 2024-2-1 22:00:37 | 显示全部楼层 |阅读模式
严格地说,赋值运算符 (=) 是二元运算符。 其声明与任何其他二元运算符的相同,但有以下例外:

它必须是非静态成员函数。 没有“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:perator=(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 开始)。

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表