JohnnyF
JohnnyF

Reputation: 1101

operation overloading * (both left side and right side)

I have a class Mat

class Mat
{
 ..
..
..
   friend Mat& operator*(Mat s1,int elem){
     s1.multiWith(elem);
     return s1;
}
};

now it will work for m1*2 but how to make it work with 2*m1

Upvotes: 3

Views: 3437

Answers (2)

songyuanyao
songyuanyao

Reputation: 172964

now it will work for m1*2 but how to make it work with 2*m1

Provide another overload for it.

class Mat
{
..
    friend Mat operator*(const Mat& s1, int elem) {
        Mat ret = s1;
        ret.multiWith(elem);
        return ret;
    }
    friend Mat operator*(int elem, const Mat& s1) {
        return s1 * elem;
    }
};

BTW1: operator* should return Mat by value, not by reference.
BTW2: You might want to change the parameter type of s1 to const reference to avoid copying.
BTW3: If Mat::multiWith is not private operator* don't have to be friend.

Upvotes: 4

jpo38
jpo38

Reputation: 21514

a*b operator is supposed to return a new object, not a reference to a.

Correct syntax to declare an operator* within the class is:

class Mat
{
   ..
   ..
   ..
   Mat operator*(int elem){
        Mat res = *this;
        res.multiWith(elem);
        return res;
   }
};

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;
}

Upvotes: 3

Related Questions