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

标签 c++

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

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;
}

最佳答案

你的 copy assignment operator应该返回对自身的引用,并进行赋值:

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

至于:

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

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

关于c++ - 练习复制构造函数和运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988655/

相关文章:

c++ - 多线程 C++ 程序未使用 vector<thread> 和 .join() 并行运行

c++ - 启动后如何结束libsoundio流?

c++ - 非平凡析构函数使类非平凡可构造

C++ Cmake boost lib不断抛出很多错误

c++ - 在 Windows 中自动播放安装 CD 时如何为 setup.exe 指定发布者

c++ - 如何在 C++ 中获取图层类型的 caffe

c++ - 如何避免重新声明子方法并仍然为不同的子类定义不同的方法?

c++ - 为什么我的字符串流是空的?

c++ - 将一段 C++ 翻译成 Python

c++ - 通过new和allocator分配内存有什么区别