运算符重载流提取运算符 (>>) C++会导致无限递归流提取
Operator overloading the stream extraction operator (>>) in C++ results in infinite recursive stream extraction
我仍在学习围绕C 的方式(我是高中生),对于竞争,我需要阅读逗号分开的价值观,我认为这将是一个整齐的机会要了解如何超载流提取器(>>)操作员,以摆脱可能在值之后出现的任何定界符。(这是我能想到的最好的方法,如果有更好的话,请分享!)但是,如标题所示,流动操作无限地递归,导致该程序崩溃。我不知道如何解决此问题,我尝试在线搜索几个小时的解决方案。这是代码:
#include <iostream>
#include <fstream>
using namespace std; // Sorry if this annoys some people
// Create a class the inherits from ifstream for file opening and stream extraction and stuff. (cStream stands for Custom Stream)
class cStream : public ifstream
{
private:
string Delimiters;
public:
cStream() : ifstream() {}
cStream(const char* filename, const char* _Delimiters = "nt ") : ifstream(filename), Delimiters(_Delimiters) {}
// Define friend functions so that the stream extractor can access the private variable Delimiters. (might not be needed but eh)
template <class t> friend cStream& operator >> (cStream&, t&); // Problem function.
};
cStream& operator >> (cStream in, const char* delimOverride)
{
in.Delimiters = delimOverride;
return(in);
}
// Operator overloaded stream extractor that gets rid of any characters in cStream.Delimiters.
// The variable names are weird but I didn't know what to name them.
template <class t> cStream& operator >> (cStream& in, t& out)
{
in >> out; // What the heck do I do here?
// The cStream stream extraction operator gets called recursively because it takes a cStream and returns a cStream,
// but how do I fix that...?
// Get rid of any trailing delimiters and spaces
while ((in.Delimiters + " ").find(in.peek()) != -1) in.ignore();
//Return with new input stream
return(in);
}
我不知道这是否是不良的代码,正如我所说,我仍在学习有关C 的信息。如果是不良的代码,请帮助我改进它。谢谢你!&lt; 3
我也是一个可以堆叠溢出的菜鸟,所以如果我做错了什么,请告诉!
in >> out; // What the heck do I do here?
那条代码线被翻译为operator>>(in, out)
,导致无限递归。
我猜您想使用基类功能阅读到out
。为此,您需要显式创建对基类的参考并使用该参考。
std::ifstream& in_f = in;
in_f >> out;
您也可以使用单线。
static_cast<std::ifstream&>(in) >> out;
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 是否需要使用 - &gt;运算符在C 中调用成员函数时