当一个类重载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+
的正确实现吗?还是我忽略了一些可能导致麻烦或不需要/未定义的行为的东西?
最佳答案
更好的是,你应该让它成为一个免费的功能:
Point operator+( Point lhs, const Point& rhs ) { // lhs is a copy
lhs += rhs;
return lhs;
}
但是,是的,如果您将它保留为成员函数,它应该是 const
,因为它不会修改左侧对象。
关于是返回引用还是拷贝,运算符重载的建议是像基本类型那样做(即像 int
那样做)。在这种情况下,两个整数的加法返回一个单独的整数,该整数不是对任何一个输入的引用。
关于C++ - 我应该使 `operator+` 为常量吗?它会返回引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13410848/