【问题标题】:Overload operator+(int) with number before object [duplicate]在对象之前用数字重载运算符+(int)[重复]
【发布时间】:2016-03-28 17:13:32
【问题描述】:

我有一个 vec2 类,定义如下

class vec2 {
public:
    float x, y;

    ...

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

operator+ 重载在执行 vec2 v = otherVector * 2.0f; 时效果很好,但在向后执行时不起作用,例如 vec2 v = 2.0f * otherVector;

解决办法是什么?

【问题讨论】:

    标签: c++


    【解决方案1】:

    以你的例子,表达式

    otherVector * 2.0f
    

    等价于

    otherVector.operator+(2.0f)
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2020-05-14
      • 2020-10-07
      • 1970-01-01
      • 2015-08-18
      • 2016-07-22
      相关资源
      最近更新 更多