[英]How to create operator*(double) for multiplying on both the left and right hand side?
I'm trying to figure out how to write an overloaded operator for my Vector2d class that allows me to multiply by a scalar on both the left and right sides. 我正在试图找出如何为我的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);
}
If I only define the member operator*, my object can be multiplied on the right by a scalar but not the left. 如果我只定义成员运算符*,我的对象可以在右边乘以标量而不是左边。 If I add the friend function operator*, I get an error when I compile:
如果我添加了友元函数运算符*,我编译时会出错:
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&)'
What's the right way to do this? 这样做的正确方法是什么?
I was putting the operator* function in the header file. 我把operator *函数放在头文件中。 Once I moved it to the .cpp, it compiled correctly.
一旦我将它移动到.cpp,它就可以正确编译。
It looks like your file has been included multiple times, most compilers support #pragma once
these days. 看起来您的文件已被多次包含,大多数编译器这些天都支持
#pragma once
。 You can also use a header guard (check for a token's definition before defining it along with the rest of your 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.