当一个类重载operator+
时,它是否应该被声明为const,因为它不会对该对象进行任何赋值? 此外,我知道operator=
和operator+=
返回一个参考,因为进行了分配。但是,operator+
呢?当我实现它时,我应该复制当前对象,将给定的对象添加到该对象,并返回该值?C++ - 我应该使`运算符+`常量?它是否会返回一个参考?
以下是我有:
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+
的?或者是否有我忽视的可能会导致麻烦或不必要的/未定义的行为?
运算符重载的很多细节可以在这里找到:http://stackoverflow.com/questions/4421706/operator-overloading – chris