我一直在练习创建复制构造函数和重载运算符,所以我想知道是否有人可以检查我的实现是否正确。这只是一个随意的练习例子。
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;
}
答案 0 :(得分:2)
您的copy assignment operator应该返回对自身的引用,并执行分配:
/signin-google
至于:
Rectangle& Rectangle::operator= (const Rectangle &right)
{
length = right.length;
width = right.width;
cout << "= operator" << endl;
return *this;
}
我建议将其显式化,以防止从整数进行隐式转换。