0

我正在尝试用 C++ 制作一个矢量类。我已经像这样重载了 * 运算符:

class vector2
{
public:
    vector2(float x, float y);

    static vector2 vector_zero;

    float x, y;
    float length() const;
    string to_string();

    vector2 operator+(vector2 other);
    vector2 operator*(float other);
};

vector2 vector2::operator*(float other)
{
    return vector2(x * other, y * other);
}

当我写“vector2(3,4)* 2”时它工作正常,但我希望它在我写“2 * vector(3,4)”时也能工作。我怎样才能做到这一点?

4

1 回答 1

0

您需要operator*像这样创建另一个(在类之外):

vector2 operator*(float other, vector2 v){
  return v*other;
}

边注:

您忘记了很多const声明,我还建议对类使用引用 ( &)。我也会制作这些函数inline,因为它们太小了:

class vector2
{
public:
...
  string to_string() const;
  inline vector2 operator+(const vector2 &other)const;
  inline vector2 operator*(float other)const;
};

inline vector2 operator*(float other, const vector2 &v){
  return v*other;
}
于 2013-07-18T15:43:59.603 回答