操作重载*(左侧和右侧) [英] operation overloading * (both left side and right side)
本文介绍了操作重载*(左侧和右侧)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个班级垫
class Mat
{
..
..
..
friend Mat& operator*(Mat s1,int elem){
s1.multiWith(elem);
return s1;
}
};
现在它适用于米1*2但如何让它工作2*m1
now it will work for m1*2 but how to make it work with 2*m1
推荐答案
a*b
运算符应该返回一个新对象,而不是对 a
的引用.
a*b
operator is supposed to return a new object, not a reference to a
.
在类中声明 operator*
的正确语法是:
Correct syntax to declare an operator*
within the class is:
class Mat
{
..
..
..
Mat operator*(int elem){
Mat res = *this;
res.multiWith(elem);
return res;
}
};
那么,左参数的类型必然是当前类(这里:a*b
的左参数必然是一个Mat
实例).
Then, type of the left parameter is necessarily the current class (here: left parameter of a*b
is necessarily a Mat
instance).
现在如果你在类外声明运算符,你可以自由选择左右参数的任何类型:
Now if you declare the operators outside the class, you are free to choose any type for left and right parameters:
class Mat
{
};
Mat operator*(const Mat& left,int right){
Mat res;
// do res=left*elem
return res;
}
Mat operator*(int left,const Mat& right){
Mat res;
// do res=left*right
return res;
}
这篇关于操作重载*(左侧和右侧)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文