Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload an operator twice [duplicate]

Tags:

c++

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?

like image 265
Guilherme Avatar asked Nov 04 '25 17:11

Guilherme


2 Answers

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.

like image 112
juanchopanza Avatar answered Nov 07 '25 05:11

juanchopanza


method overload in C++ is by argument list, not the return value.. so in your case, the two methods are ambiguous and the compiler can't tell which one to use (they have the same argument list)

like image 29
NirMH Avatar answered Nov 07 '25 07:11

NirMH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!