Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloaded operator with reverse order of associativity

It was very hard to come up with a title... (I'm not a native English speaker.)

struct A
{
    int value;
    A operator+(int i) const
    {
        A a;
        a.value=value+i;
        return a;
    };
};
int main(){
    A a;
    a.value=2;
    a=a+2;
    return 0;
}

This code compiles/works as expected, but when I change a=a+2 to a=2+a, it won't compile anymore. GCC gives me this error:

no match for ”operator+” in ”2 + a”

Is there any way to somehow make 2+a work just like a+2?

like image 570
Hassedev Avatar asked Apr 20 '13 09:04

Hassedev


1 Answers

You need a free function, defined after the class

struct A
{
   // ...
};

A operator+(int i, const A& a)
{
  return a+i; // assuming commutativity
};

also, you might consider defining A& operator+=(int i); in A an implement both versions of operator+ as free functions. You might also be interested in Boost.Operators or other helpers to simplify A, see my profile for two options.

like image 105
Daniel Frey Avatar answered Sep 28 '22 13:09

Daniel Frey