C++ - 我应该使 `operator+` 为常量吗?它会返回引用吗?

标签 c++ oop reference operators operator-overloading

当一个类重载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/

相关文章:

c++ - 寻找关于指针使用差异的一些确认

c++ - 有没有办法动态更改比较运算符?

perl - 如何在 Moose 中声明/使用静态成员?

design-patterns - 出色的软件设计和实现示例

javascript - 从另一个上下文调用方法时,`this` 未定义

rust - 为什么不能在同一结构中存储值和对该值的引用?

c++ - getter 和 setter 的错误

c++ - VC++ 运行时错误 : Debug Assertation Failed

c++ - 检查是否所有变量都等于 C++ 中的相同值

java - 从方法返回值时,这两个语句有什么区别?