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

时间:2019-03-03 18:16:28

标签: c++ operator-overloading

我仍在学习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 = "\n\t\0") : 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 ++。如果代码错误,请帮助我进行改进。谢谢! <3

我也是Stack Overflow的菜鸟,因此,如果我做错了什么,请告诉我们!

1 个答案:

答案 0 :(得分:0)

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;