C++ 重载 * 运算符 - 必须采用零个或一个参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13544364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Over loading * operator - must take either zero or one arguments
提问by Mohammad Jafar Mashhadi
I'm new to overloading operators, I did some search and found this helpful article, I wrote my own code like the author did but I get vector vector::operator*(float, vector) must take either zero or one argument
error.
我是重载运算符的新手,我做了一些搜索并找到了这篇有用的文章,我像作者一样编写了自己的代码,但vector vector::operator*(float, vector) must take either zero or one argument
出现错误。
Here is my code:
这是我的代码:
class vector
{
public:
float x;
float y;
vector(float, float);
float operator$ (vector, vector);
vector operator* (float, vector);
vector operator* (vector, float);
};
vector::vector(float _x = 0, float _y = 0)
{
x = _x;
y = _y;
}
const float vector::operator$ (const vector &v1, const vector &v2)
{
return (v1.x * v2.x) + (v1.y * v2.y);
}
const vector vector::operator* (const float &m, const vector &v)
{
vector ret_val = v;
ret_val.x *= m;
ret_val.y *= m;
return ret_val;
}
const vector vector::operator* (const vector &v, const float &m)
{
return m * vector;
}
My operating system is kubuntu 12.04
and my IDE is dev-C++
running on linux using wine windows program loader.
我的操作系统是kubuntu 12.04
,我的 IDEdev-C++
使用 wine windows 程序加载器在 linux上运行。
回答by chrisaycock
Because you are defining operator*()
as a member function, there is already one implicit parameter: the object for which the method is invoked! Therefore, member functions take one explicit parameter, not two.
因为您定义operator*()
为成员函数,所以已经有一个隐式参数:调用方法的对象!因此,成员函数采用一个显式参数,而不是两个。
回答by ajp013
Just declare your operator overload function outside the class. Also you are returning a const which might not be what you want.
只需在类外声明您的运算符重载函数即可。此外,您正在返回一个可能不是您想要的常量。
class foo {
//code
};
foo operator*(foo& lhs, bar& rhs) const;
foo operator*(bar& lhs, foo& rhs) const;