练习复制构造函数和运算符重载

Practice Copy Constructor and Operator Overloading

本文关键字:运算符 重载 构造函数 复制 练习      更新时间:2023-10-16

我一直在练习创建复制构造函数和重载运算符,所以我想知道是否有人可以检查我的实现是否正确。这只是一个武断的实践例子。

class Rectangle
{
    private:
        int length;
        int width;
    public:
        Rectangle(int len = 0, int w = 0)
        {
            length = len;
            width = w;
        }
        Rectangle(const Rectangle &);
        Rectangle operator + (const Rectangle &);
        Rectangle operator = (const Rectangle &);
};
Rectangle::Rectangle(const Rectangle &right)
{
    length = right.length;
    width = right.width;
    cout << "copy constructor" << endl;
}
Rectangle Rectangle::operator + (const Rectangle &right)
{
    Rectangle temp;
    temp.length = length + right.length + 1;
    temp.width = width + right.width + 1;
    cout << "+ operator" << endl;
    return temp;
}
Rectangle Rectangle::operator = (const Rectangle &right)
{
    Rectangle temp;
    temp.length = right.length + 2;
    temp.width = right.width + 2;
    cout << "= operator" << endl;
    return temp;
}

您的复制赋值操作符应该返回对自身的引用,并执行赋值:

Rectangle& Rectangle::operator= (const Rectangle &right)
{
    length = right.length;
    width = right.width;
    cout << "= operator" << endl;
    return *this;
}

对于:

Rectangle(int len = 0, int w = 0)

我建议将其显式化,以防止整数的隐式转换。