当一个类重载operator+
时,是否应该将其声明为 const,因为它不对对象进行任何赋值?另外,我知道这一点operator=
并operator+=
返回一个参考,因为已经进行了分配。但是,怎么operator+
办?当我实现它时,我是否应该复制当前对象,将给定对象添加到该对象,然后返回该值?
这是我所拥有的:
class Point
{
public:
int x, int y;
Point& operator += (const Point& other) {
X += other.x;
Y += other.y;
return *this;
}
// The above seems pretty straightforward to me, but what about this?:
Point operator + (const Point& other) const { // Should this be const?
Point copy;
copy.x = x + other.x;
copy.y = y + other.y;
return copy;
}
};
这是正确的实现operator+
吗?还是我忽略了一些可能导致麻烦或不需要/未定义的行为的东西?