C++ overloaded operator with reverse order of associativity
Asked Answered
G

3

9

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?

Goahead answered 20/4, 2013 at 9:52 Comment(0)
S
11

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.

Sheared answered 20/4, 2013 at 9:55 Comment(1)
Works perfectly! I forgot to make the operator+ in A const, I'll fix it now.Goahead
G
4

Sure, define the inverse operator outside the class:

struct A
{
    int value;
    A operator+(int i) const
    {
        A a;
        a.value=value+i;
        return a;
    };
};
//marked inline to prevent a multiple definition
inline A operator+(int i, const A& a)
{
    return a + i;
}
Geometrize answered 20/4, 2013 at 9:56 Comment(0)
I
0

The other answers here work fine. However, another option you have is to create a constructor for a single int like this:

struct A
{
    int value;
    A(int i) {
        value = i;
    }
};

This allows integers to get implicitly converted, and allows you to only overload operators for your struct instead:

A operator+(const A& other) const
{
    // All you need to do is work with an A, and associativity works fine
};

Of course, this does allow all integers to get implicitly converted to As, which may or may not be desirable.

Inbreathe answered 28/11, 2019 at 0:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.