C++ overloaded operator with reverse order of associativity -
it hard come title... (i'm not native english speaker.)
struct { int value; operator+(int i) const { a; a.value=value+i; return a; }; }; int main(){ a; a.value=2; a=a+2; return 0; }
this code compiles/works expected, when change a=a+2 a=2+a, won't compile anymore. gcc gives me error:
no match ”operator+” in ”2 + a”
is there way somehow make 2+a work a+2?
you need free function, defined after class
struct { // ... }; operator+(int i, const a& a) { return a+i; // assuming commutativity };
also, might consider defining a& operator+=(int i);
in a
implement both versions of operator+
free functions. might interested in boost.operators or other helpers simplify a
, see profile 2 options.
Comments
Post a Comment