![](/img/trans.png)
[英]“recursive on all control paths, function will cause runtime stack overflow” on overloaded << operator
[英]Why does the compiler report "operator<< and operator>> recursive on all control paths will cause stack overflow "?
#include <iostream>
class fraction {
int n, d;
public:
fraction(){}
fraction(int n, int d) : n(n), d(d) {}
int getter() { return n, d; }
friend std::istream& operator>>(std::istream& stream, const fraction& a) {
stream >> a;
return stream;
}
friend std::ostream& operator<<(std::ostream& stream, const fraction& a) {
stream << a;
return stream;
}
friend fraction operator*(const fraction& a, const fraction& b) {
int pN = a.n * b.n;
int pD = b.n * b.d;
return fraction(pN, pD);
}
};
int main()
{
fraction f1;
std::cout << "Enter fraction 1: ";
std::cin >> f1;
fraction f2;
std::cout << "Enter fraction 2: ";
std::cin >> f2;
std::cout << f1 << " * " << f2 << " is " << f1 * f2 << '\n'; // note: The result of f1 * f2 is an r-value
return 0;
}
編譯錯誤說:
operator<< and operator>> recursive on all paths, function will cause a stack overflow
我不知道這是什么意思。 在所有路徑上遞歸是什么意思,哪個函數會導致堆棧溢出?
當你運行時:
stream >> a;
您正在調用正在運行的相同函數,即friend std::istream& operator>>(std::istream& stream, const fraction& a)
。
所以你會一次又一次地叫自己(遞歸),一次又一次......沒有結束。 反過來,這意味着分配給堆棧的內存將在某個時候耗盡(因為每個幀都占用一些空間)並且會導致堆棧溢出。
相反,您必須對fraction
參數a
做一些事情,最有可能引用an
和ad
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.