运算符重载流提取运算符 (>>) C++会导致无限递归流提取

Operator overloading the stream extraction operator (>>) in C++ results in infinite recursive stream extraction

本文关键字:gt 运算符 提取 无限 递归 C++ 重载      更新时间:2023-10-16

我仍在学习围绕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;