c++ - 为什么编译器报告 "operator<< and operator>> recursive on all control paths will cause stack overflow "?

标签 c++ recursion 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)

因此您将一次又一次地调用自己(递归)...没有尽头。反过来,这意味着分配给 堆栈 的内存将在某个时候耗尽(因为每个 frame 占用一些空间)并且它会导致 堆栈溢出

相反,您必须对 fraction 参数 a 做一些事情,很可能是指 a.na.d.

关于c++ - 为什么编译器报告 "operator<< and operator>> recursive on all control paths will cause stack overflow "?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401657/

相关文章:

c++ - C 和 C++ 中的翻译单元

c++ - 我的 dll 中没有资源。但是为什么我的 dll 中的 .rdata 部分这么大?

java - 如何使用递归计算树中的最高级别?

java - 二分查找期间堆栈溢出

java - 洪水填充 StackOverFlow、IDEA

c++ - 谁应该拥有迭代器、我的数据类或该类中的实际列表?

C++ 内部类不编译

php - 递归遍历数组并打印遍历路径

python - **recurPower** 我明白了,但我不明白

c# - ServiceStack接收大数据时抛出StackOverflowException