重载对象前面带有数字的运算符+(int)

Overload operator+(int) with number before object

本文关键字:运算符 int 数字 对象 前面 重载      更新时间:2023-10-16

我有一个vec2类,定义如下

class vec2 {
public:
    float x, y;
    ...
    //add a scalar
    vec2 operator+(float s) const {
            return vec2(this->x + s, this->y + s);
        }
};

运算符+重载在执行vec2 v = otherVector * 2.0f;时效果良好,但在向后执行时不起作用,就像vec2 v = 2.0f * otherVector;一样。

解决这个问题的办法是什么?

以您的示例为例,表达式

otherVector * 2.0f

相当于

otherVector.operator+(2.0f)

将重载运算符创建为成员函数only允许对象位于左侧,右侧传递给函数。

简单的解决方案是添加另一个运算符重载,作为非成员函数

vec2 operator+(float f, const vec2& v)
{
    return v + f;  // Use vec2::operator+
}