C++中的深拷贝问题

问题描述

所以我有一个 Rectangle 类,其重载 operator= 定义如下:

    Rectangle& Rectangle::operator=(Rectangle &rhs)
{
    if (this != &rhs)
    {
        m_x = rhs.m_x;
        m_y = rhs.m_y;
        m_width = rhs.m_width;
        m_height = rhs.m_height;
        m_intersection = rhs.m_intersection;
    }
    return *this;
}

到目前为止,编译器没有抱怨。但是当我尝试做任务时,我的编译器抱怨:

m_boundingBox = Rectangle(x,y,width,height);

现在我试图避免调用 new,因此以这种方式分配。我假设我需要为这种赋值实现一个单独的复制构造函数,但我不知道签名应该是什么样子。

这是编译器错误错误(活动)E0349 没有运算符“=”匹配这些操作数

首先,我想解决上述问题。但其次,如果你能对这个困惑的代码编写猿人的整个主题有所了解,那就太棒了。教人钓鱼等等。

解决方法

您的问题是您尚未声明参数 const。应该是这样的:

Rectangle& Rectangle::operator=(const Rectangle &rhs)