Bra*_*ler 5 c++ oop reference operator-overloading operators
当一个类重载时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;
}
};
Run Code Online (Sandbox Code Playgroud)
这是正确的实施operator+吗?或者有什么我忽略的可能会导致麻烦或不必要的/未定义的行为?
更好的是,你应该让它成为一个自由的功能:
Point operator+( Point lhs, const Point& rhs ) { // lhs is a copy
lhs += rhs;
return lhs;
}
Run Code Online (Sandbox Code Playgroud)
但是,是的,如果你把它作为一个成员函数,它应该是const因为它不会修改左侧对象.
关于是否返回引用或副本,操作符重载的建议是按照基本类型进行的(即按照ints做).在这种情况下,对两个整数的加法返回一个单独的整数,该整数不是对任何一个输入的引用.