Question

I'm working in a Big Integer implementation in C++ and I'm trying to use cout with my BigInt class. I already overloaded the << operator but it doesn't work in some cases.

Here is my code:

inline std::ostream& operator << (ostream &stream, BigInt &B){

    if (!B.getSign()){
        stream << '-';
    }
    stream << B.getNumber();

    return stream;
}

The code above works with:

c = a + b;
cout << c << endl;

But fails with:

cout << a + b << endl;

In the first case the program runs fine, but in the second the compiler gave an error:

main.cc: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

It's possible to overload the << operator for function in both cases?

Methods:

string getNumber ();
bool getSign ();

string BigInt::getNumber (){
  return this->number;
}

bool BigInt::getSign (){
  return this->sign;
}
Was it helpful?

Solution

As chris already pointed out in comments very quickly (as usual), you have a temporary created in here:

cout << a + b << endl;

You cannot bind that to a non-const reference. You will need to change the signature of your operator overloading by adding the const keyword to the reference.

This code works for me with a dummy BigInt implementation (as you have not shared yours):

#include <iostream>

using namespace std;

class BigInt
{
    public:
    bool getSign() const { return true; }
    int getNumber() const { return 0; }
    const BigInt operator+(const BigInt &other) const {}
};

inline std::ostream& operator << (ostream &stream, const BigInt &B){
//                                                 ^^^^^
    if (!B.getSign()){
        stream << '-';
    }
    stream << B.getNumber();

    return stream;
}

int main()
{
    BigInt a, b, c;
    c = a + b;
    cout << c << endl;
    cout << a + b << endl;
    return 0;
}

But yeah, I agree that the error message is not self-explanatory in this particular case.

OTHER TIPS

Change

inline std::ostream& operator << (ostream &stream, BigInt &B){

to

inline std::ostream& operator << (ostream &stream, BigInt const& B){

c can be a used where BiInt& is expected but a+b cannot be because a+b is a temporary. But it can be used where BigInt const& is expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top