2015-12-21 21 views
4

好吧,我認爲這可能只是一個版本問題,但我是新手。我有一個使用我重寫<<運營商的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++,以便它可以工作?

回答

13
ostream & operator<<(ostream& os, BigInt& num) 

應該採取BigInt const& numMSVC is non-compliant with regards to this。 g ++沒有這個擴展名。

確保您更改標題中的聲明和BigInt.c文件中的定義。 (另外,這是正常使用含有C++代碼文件.c含有C代碼文件,和.cpp。)

的原因是,(a+a)創建臨時BigInt,這是不能被綁定到一個非const參考。第一個cout的工作原理是因爲a是一個局部變量,而不是一個臨時變量,因此可以作爲普通(非const)引用傳遞。

除了臨時性問題外,最好還是應用const-correctness:製作東西const,除非您確實需要更改它們。這可以幫助防止錯誤。請注意,std::ostream& os不能是const,您確實通過寫入來更改它。

6

的問題是與

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

既然你採取BigInt& num這不會與(a+a)工作作爲包裝箱臨時,你不能拿一個臨時的參考。它在MSVS as they have an extension to allow this工作,但g ++沒有。將其更改爲

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

那麼,爲什麼第一COUT工作,但不是第二個?

您的operator <<通過非const引用獲取其第二個參數。臨時像(a+a)無法綁定到,所以第二個電話是非法的。 MSVC允許作爲擴展,但它不是標準的C++。

有沒有辦法來運行g ++,使它可以工作?

否修復您的運算符以改爲使用const引用。

相關問題