首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么编译器报告“所有控制路径上的operator<<和operator>>递归将导致堆栈溢出"?

为什么编译器报告“所有控制路径上的operator<<和operator>>递归将导致堆栈溢出"?
EN

Stack Overflow用户
提问于 2019-12-19 08:07:04
回答 1查看 57关注 0票数 0
代码语言:javascript
运行
复制
#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;
}

编译错误说:

代码语言:javascript
运行
复制
operator<< and operator>> recursive on all paths, function will cause a stack overflow

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

EN

Stack Overflow用户

发布于 2019-12-19 08:08:56

当你运行时:

代码语言:javascript
运行
复制
stream >> a;

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

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

相反,您必须对fraction参数a做一些操作,很可能引用a.na.d

票数 3
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59401657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档