c++ - 为什么编译器会报告“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
,很可能是指a.n
和a.d
。
推荐阅读
- bash - Bash:通过for-in-loop执行文件
- angular6 - NGXS - 使用 redux devtools 插件/记录器的 Angular 6 过滤表单操作
- excel - 如果单元格值等于:“失败”,则关闭时 Excel 中的 VBA 代码消息框
- ios - 在哪里检查“如果我使用 v4.29.0 或更高版本的 SDK,则需要添加:”
- apache-kafka - 关于 Kafka 中的分区和解决方案架构的说明
- r - 使用新数据框从表中预测线性模型
- java - 如何修复在类路径中找不到类
- angular - 在Angular4中自动将一个页面导航到另一个页面
- java - 使用 JPA 获取数据库用户并在 Entity Attribute 中设置
- user-interface - 在 simplesamlphp 中使用 Twig