我試圖重載< <運營商檢測操作的溢出,下面是我的代碼的部分新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)
和突破點就在運營商< <的實施出現。但我無法弄清楚我應該嘗試着解決這個問題。
有人可以告訴我這是什麼原因?
等等......你*意欲*爲無窮遞歸'運算符<<'?因爲那*完全是*你編碼的東西。 – WhozCraig
這個「異常」不是C++異常,你不能用catch來捕捉異常。 – aschepler