c++ - 如何创建 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,它就正确编译了。
解决方案
看起来您的文件已被多次包含,现在大多数编译器都支持#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
推荐阅读
- ios - 如何在 Xcode 中更新或安装最新版本的 IOS?
- duktape - 从 Duktape 调用的 C++ 函数中的错误捕获和恢复
- html - 如何更改 IE 11 滚动条的宽度?
- c++ - 没有定义的自动变量声明
- javascript - 如何在节点 js 中多次覆盖和追加数据到同一个文件
- kubernetes - oauth2 代理边车的目的是什么?
- php - Laravel 5.6: ErrorException: compact(): Undefined variable: operator
- xml - 如何从 XmlEvent 访问 XML 元素名称
- flutter - 当该属性更改时,如何对显示对象属性的文本小部件进行反应性更新?这与 GetX
- elasticsearch - 如何在一个仪表板kibana中显示不同的时间段?