G ++ compiler gives << type errors for expressions, but works in Visual Studio

Ok, I think this might be a version issue, but I'm new to this. I have a main file that uses my overridden statement <<for the class BigIntthat I implemented:

BigInt a = 3;
cout << a << endl;
cout << (a+a) << endl;

In Visual Studio, the compiler understands everything perfectly and works great. But going to Ubuntu 14.04, makeing with my Makefile (which uses simple commands g++) gives me bazillion errors caused by the third line (and any other line using cout with an expression). If I delete the third line, it compiles fine. First mistake:

main.cpp:23:8: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'BigInt')
    cout << (a+a);
         ^

, << args:

// in BigInt.h, in class' public section:

BigInt operator+(BigInt const& other) const;
friend std::ostream & operator<<(std::ostream& os, BigInt& num);


// in BigInt.cpp:

BigInt BigInt::operator+(BigInt const& other) const {
    // call appropriate helper based on signs
    if (this->neg == other.neg) {
        return sum(other);
    }
    else {
        return difference(other);
    }
}

ostream & operator<<(ostream& os, BigInt& num) {
    if (num.dataLength == -1) {
        os << "**UNDEFINED**";
    }
    else {
        if (num.neg) os << "-";
        if (num.dataLength == 0) {
            os << "INFINITY";
        }
        else {
            // print each digit
            for (int i = num.dataLength - 1; i >= 0; i--) {
                os << (short)num.data[i];
            }
        }
    }
    return os;
}

, cout , ? g++, ?

+4
3
ostream & operator<<(ostream& os, BigInt& num)

BigInt const& num. MSVC . g++ .

, , BigInt.c. ( .c , C, .cpp , C++ code.)

, (a+a) BigInt, const. cout , a - , , ( const) .

, const -correctness: const, . . , std::ostream& os const, , .

+13

friend std::ostream & operator<<(std::ostream& os, BigInt& num);

BigInt& num, (a+a), . MSVS, , , g++ .

friend std::ostream & operator<<(std::ostream& os, const BigInt& num);
+6

, cout , ?

Your operator <<takes its second argument with a non-constant reference. Temporary users (a+a)cannot seem to be attached to this, so the second call is illegal. MSVC allows this as an extension, but is not standard C ++.

Is there a way to run g ++ so that it can work?

No. Correct your statement to use the const reference instead.

+6
source

Source: https://habr.com/ru/post/1621138/


All Articles