好吧,我認爲這可能只是一個版本問題,但我是新手。我有一個使用我重寫<<
運營商的BigInt
類,我實現了一個主文件:g ++編譯器爲表達式提供<<類型錯誤,但在Visual Studio中工作
BigInt a = 3;
cout << a << endl;
cout << (a+a) << endl;
在Visual Studio中,編譯器明白一切就好了,它運行偉大。但移動到我的Makefile(使用普通的g++
命令)的Ubuntu 14.04,make
給我一個bazillion類型的錯誤是由第三行(和任何其他使用cout表達式的行)引起的。如果我刪除第三行,它編譯得很好。第一個錯誤是:
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++
,以便它可以工作?