[英]Practice Copy Constructor and Operator Overloading
I've been practicing creating copy constructors and overloading operators, so I was wondering if someone could check if my implementation is correct. 我一直在练习创建副本构造函数和重载运算符,所以我想知道是否有人可以检查我的实现是否正确。 This is just an arbitrary practice example.
这只是一个任意的练习示例。
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;
}
Your copy assignment operator should return a reference to itself, and also do the assignment: 您的副本分配运算符应返回对自身的引用,并进行分配:
Rectangle& Rectangle::operator= (const Rectangle &right)
{
length = right.length;
width = right.width;
cout << "= operator" << endl;
return *this;
}
as for: 至于:
Rectangle(int len = 0, int w = 0)
I recomend making it explicit, to prevent implicit conversions from integer. 我建议使其明确,以防止从整数进行隐式转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.