首页 > 解决方案 > 如何创建 operator*(double) 以在左侧和右侧进行乘法运算?

问题描述

我试图弄清楚如何为我的 Vector2d 类编写一个重载运算符,它允许我在左侧和右侧乘以一个标量。

class Vector2d
{
    double _x;
    double _y;

public:
    Vector2d(double x = 0, double y = 0) :_x(x), _y(y) {}

    Vector2d operator*(const double s) const
        { return Vector2d(_x * s, _y * s); }

    friend Vector2d operator*(const double s, const Vector2d& v);
};

Vector2d operator*(const double s, const Vector2d& v)
{
    return Vector2d(v._x * s, v._y * s);
}

如果我只定义成员运算符*,我的对象可以在右侧乘以标量,但不能在左侧乘以。如果我添加友元函数 operator*,我会在编译时出错:

Vector2D.h:61: multiple definition of `Gf::operator*(double, Gf::Vector2d const&)'
Vector2D.h:61: first defined here
Vector2D.h:61: multiple definition of `Gf::operator*(double, Gf::Vector2d const&)'

这样做的正确方法是什么?


我将 operator* 函数放在头文件中。一旦我将它移到 .cpp,它就正确编译了。

标签: c++operator-overloading

解决方案


看起来您的文件已被多次包含,现在大多数编译器都支持#pragma once。您还可以使用标头保护(在与标头的其余部分一起定义之前检查令牌的定义):

#ifndef VECTOR_2D
#define VECTOR_2D

class Vector2d
{
    double _x;
    double _y;

public:
    Vector2d(double x = 0, double y = 0) :_x(x), _y(y) {}

    Vector2d operator*(const double s) const
        { return Vector2d(_x * s, _y * s); }

    friend Vector2d operator*(const double s, const Vector2d& v);
};

Vector2d operator*(const double s, const Vector2d& v)
{
    return Vector2d(v._x * s, v._y * s);
}

#endif // VECTOR_2D

推荐阅读