Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top