c++ - 如何创建 operator*(double) 以在左侧和右侧进行乘法运算?

标签 c++ operator-overloading

我正在尝试弄清楚如何为我的 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,它就可以正确编译。

最佳答案

看起来你的文件被包含了多次,大多数编译器都支持#pragma once这些日子。您还可以使用 header 保护(在定义标记的定义之前检查标记的定义以及 header 的其余部分):

#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

关于c++ - 如何创建 operator*(double) 以在左侧和右侧进行乘法运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585467/

相关文章:

c++ - 在 C/C++ 中将文件重命名为 unicode 名称

c++ - 是否有一个 std::string 函数来附加空格直到给定的缩进级别

c++ - 运算符关键字和运算符重载模拟

c++ - 指针数组的问题

c++ - 运算符重载器没有影响

c++ - 重载 + 运算符以组合两个使用 vector 的字典

C++ 标准库串行端口 (UART) 接口(interface)

c++ - 如何将我的字符串更改为 int 以供我们提供给套接字

c++ - 为稀疏 vector 重载运算符 []

c++ - 我可以为自定义 Qt UI 元素定义自定义 CSS/QSS 属性吗?