2017-04-17 76 views
0

我試圖重載< <運營商檢測操作的溢出,下面是我的代碼的部分新Integer類:超載時未處理的異常<<操作

class NewInteger{ 
       private: 
       int num; 

       public: 
       NewInteger(); 
       NewInteger(int); 
       friend std::ostream &operator <<(std::ostream& out, const NewInteger& rhs); 
       NewInteger operator+ (NewInteger); 

       .../ many other member functions/ 
      } 

實現方案是

NewInteger NewInteger::operator+(NewInteger n) 
{ 
    int a = this->getValue(); 
    int b = n.getValue(); 
    if (a > 0 && b > max - a) { 
     throw std::exception(); 
     std::cout << "studpid" << std::endl; 
    } 
    if (a < 0 && b < min - a) { 
     throw std::exception(); 
    } 

    return NewInteger(a + b); 
} 
    std::ostream & operator<<(std::ostream & out, const NewInteger& rhs) 
    { 
     out << rhs; 
     return out; 
    } 

在main.cpp中,我試圖通過運行測試代碼:

NewInteger n7(4); 
    NewInteger n8(5); 
    std::cout << n7.operator+(n8) << std::endl; 

代碼生成良好,當我在Visual Studio 2015上運行它時,它會導致程序關閉而不會發生致命錯誤。所以,當我調試的代碼,它給了我:`

Exception thrown at 0x00C43B49 in NewInteger.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00192F90) 

和突破點就在運營商< <的實施出現。但我無法弄清楚我應該嘗試着解決這個問題。

有人可以告訴我這是什麼原因?

+2

等等......你*意欲*爲無窮遞歸'運算符<<'?因爲那*完全是*你編碼的東西。 – WhozCraig

+1

這個「異常」不是C++異常,你不能用catch來捕捉異常。 – aschepler

回答

4
std::ostream & operator<<(std::ostream & out, const NewInteger& rhs) 
{ 
    out << rhs; 
    return out; 
} 

的第一行調用operator<<outrhs - 這是你定義的功能。你有無限的遞歸。

+0

這是有道理的。我應該用什麼替換它?模板代碼在我們的類中提供的示例代碼中完全像這樣編寫的。 – dezdichado

+1

我會用'out << rhs.num;' – aschepler

+0

這樣的東西來感謝很多。有效 – dezdichado