简单的 C++:如何重载乘法运算符,以便 float*myClass 和 myClass*float 工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10354886/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:56:08 来源:igfitidea点击:
simple c++: How to overload the multiplication operator so that float*myClass and myClass*float works
提问by user52343
class MyClass;
int main()
{
float a = 5;
MyClass c1;
MyClass c2 = a*c1;
MyClass c3 = c1*a;
}
How can I overload the multiply operator so that both a*c1 and c1*a work?
如何重载乘法运算符以便 a*c1 和 c1*a 都能工作?
回答by Luchian Grigore
Like so:
像这样:
MyClass operator* (float x, const MyClass& y)
{
//...
}
MyClass operator* (const MyClass& y, float x)
{
//...
}
The second one can also be a member function:
第二个也可以是成员函数:
class MyClass
{
//...
MyClass operator* (float x);
};
The first 2 options work as declarations outside of class scope.
前 2 个选项用作类范围之外的声明。