简单c ++:如何重载乘法运算符,使float * myClass和myClass * float工作 [英] simple c++: How to overload the multiplication operator so that float*myClass and myClass*float works
本文介绍了简单c ++:如何重载乘法运算符,使float * myClass和myClass * float工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class MyClass;
int main()
{
float a = 5;
MyClass c1;
MyClass c2 = a * c1;
MyClass c3 = c1 * a;
}
如何重载multiply操作符,使a * c1和c1 *
如下:
code> MyClass operator *(float x,const MyClass& y)
{
// ...
}
MyClass操作符* ; y,float x)
{
// ...
}
$ b b
第二个也可以是成员函数:
class MyClass
{
/ / ...
MyClass operator *(float x);
};
前两个选项作为类范围之外的声明。
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?
解决方案
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.
这篇关于简单c ++:如何重载乘法运算符,使float * myClass和myClass * float工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文