为什么编译器会在所有控制路径上报告“ operator <>递归会导致堆栈溢出”?

问题描述 投票:0回答:1
#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

我不知道这意味着什么。在所有路径上递归是什么意思,哪个函数会导致堆栈溢出?

c++ recursion stack-overflow
1个回答
3
投票

运行时:

stream >> a;

您正在调用正在运行的相同功能,即friend std::istream& operator>>(std::istream& stream, const fraction& a)

所以您将一遍又一遍又一遍地...无休止地打电话给自己(递归)。反过来,这意味着分配给stack的内存将在某个时刻耗尽(因为每个frame占用一些空间),并且将导致stackoverflow

相反,您必须对fraction参数a做一些事情,最有可能引用a.na.d

© www.soinside.com 2019 - 2024. All rights reserved.