Hi,
I found a problem with operator overloading. Consider following class:

class Number
{
 public:
     int value;
     int operator +(int v)
     { return value + v; }
};

Number n; n.value = 5;

Now, n+5 successfuly returns 10, but 5+n gives error

error C2677: binary '+' : no global operator found which takes type ...

How to solve it?

Recommended Answers

All 2 Replies

Your operator overload defines an operator for Number + int, not for int + Number. Even though mathematically, addition is commutative, the compiler does not assume it is because you could define an addition operator that shouldn't be commutative.

Anyways, to solve the problem, you should define two operators, one for each case. Now, the int + Number version cannot be a member function, i.e., it cannot be a member of the "int" type, so it has to be a free-function. And usually, the other one should too. As so:

class Number
{
 public:
     int value;
};

inline int operator +(Number n, int v) { 
  return n.value + v; 
}

inline int operator +(int v, Number n) { 
  return n.value + v; 
}
commented: thanks +0

You may be wondering why two + operators are required? Try reading this link, it may clear up some of your confusion.

http://www.bogotobogo.com/cplusplus/this_pointer.html

I should clarify that Mike 2k's solution doesn't require this explanation because both + operators are defined outside of the class Number but if you had a class something like below:

#include <iostream>

class Number
{

public:

    Number():itsvalue(0) {}
    Number(int val):itsvalue(val) {}

    Number operator +(const Number & a) const { return itsvalue + a.itsvalue; }

    int getitsvalue() const { return itsvalue; }

private:

    int itsvalue;

};

Number operator +(const int val, const Number & n) { return val + n.getitsvalue(); }

std::ostream& operator <<(std::ostream & out, const Number & n)
{
    return out << n.getitsvalue();
}

int main(int argc, char** argv)
{
    int x = 123;
    Number my_n(789);

    std::cout << x + my_n << std::endl;
    std::cout << my_n + x << std::endl;
    return 0;
}

Then the explanation does make sense.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.