Overload an operator twice

c++

Solution

As has been pointed out, you cannot overload beased on return type alone. So this is fine:

Foo operator+(const Foo&, const Foo&);
Foo operator+(const char*, double);

but this is not:

Foo operator+(const Foo&, const Foo&);
Bar operator+(const Foo&, const Foo&);

But most of the time there are valid and simple solutions to a given problem. For instance, in a situation like yours, where you want the following to work:

Foo a, b;
Foo c = a + b;
Bar bar = a + b;

then a common strategy is to either give `Bar` an implicit converting constructor:

struct Bar
{
  Bar(const Foo& foo) { .... }
};

or give `Foo` a conversion operator:

struct Foo
{
  explicit operator Bar() { .... }
  ....
};

Note you can't mark the operator `explicit` if you don't have a C++11 compiler.

Problem

It's possible to overload the same operator twice on C++? When I try to overload the + operator using the return type as a base, the compiler show me an error. ``` bigint.h:41:9: error: ‘std::string BigInt::operator+(BigInt)’ cannot be overloaded bigint.h:40:9: error: with ‘BigInt BigInt::operator+(BigInt)’ ``` This is my code: .h: ``` BigInt operator + (BigInt); string operator + (BigInt); ``` .cc: ``` BigInt BigInt::operator + (BigInt M){ if (this->number.size() != M.number.size()) fixLength (this->number, M.number); // Call Sum; this->number = Sum (this->number, M.number); return (*this); } string BigInt::operator + (Bigint M){ // Call BigInt overload +; } ``` Edit: Apparently I cannot overload the same operator twice using the return type as a base. Suggestions?

Original source

Related problems