Overloading + operator in C ++

Ok, I'm working on a book and trying to learn how to overload a C ++ statement. I created a BigInt class that takes one int (initially set to 0) for the constructor. I overloaded the + = method and it works fine in the following code:

BigInt x = BigInt(2);
x += x;
x.print( cout );

The code will be output 4. So, then I worked on overloading the global + operator with the following code:

BigInt operator+(const BigInt lhs, const BigInt rhs)
{
    BigInt returnValue(lhs);
    returnValue += rhs;
    return returnValue;
}

This is also great for the following code:

BigInt x = BigInt(1);
BigInt y = BigInt(5);
BigInt z = x + y;
z.print();

This prints 6. However, when I try to execute the following code, it just doesn't work. The book does not explain very well and implies that it should just work.

BigInt x = BigInt(1);
BigInt z = x + 5;
z.print();

1. , z 1, 6. googled stackoverflow, - , . , . !

+5
4

, +=. .

+3

int BigInt; 5 int, BigInt. - :

BigInt operator+(const BigInt lhs, const int rhs)
{
    BigInt returnValue(rhs);
    returnValue += lhs;
    return returnValue;
}

, operator+(const int lhs, const BigInt rhs).

+2

- (, , ):

#include <iostream>

class BigInt
{
  public:
    BigInt(int i): _i(i) {}
    void print() { std::cout << "BigInt(" << _i << ")\n"; }
    void operator +=(const BigInt rhs) { _i += rhs._i; }
  private:
    int _i;
};

BigInt operator+(const BigInt lhs, const BigInt rhs)
{
    BigInt returnValue(lhs);
    returnValue += rhs;
    return returnValue;
}

int main() {
  BigInt x = BigInt(1);
  BigInt y = BigInt(5);
  BigInt z = x + y;
  z.print();

  BigInt ax = BigInt(1);
  BigInt az = ax + 5;
  az.print();

  return 0;
}

, :

BigInt(6)
BigInt(6)

The request to make the smallest possible changes to this working code in order to reproduce the error that you are observing - this, of course, will show where exactly your error is.

+1
source

The code you posted looks great and should work. The problems you see are almost certainly related to the copy constructor or assignment operator of your BigInt class.

0
source

All Articles