gpt4 book ai didi

c++ - 如何将文件流作为类成员

转载 作者:行者123 更新时间:2023-11-27 23:04:07 24 4
gpt4 key购买 nike

我有以下在 Visual C++ 中工作的解析器类

class Parser
{
private:
const char* filename;
std::ifstream filestream;
std::vector<std::string> tokens;
unsigned int linect;

public:
Parser(const char* filename);
bool readline();
std::string getstrtoken(unsigned int i) const { return tokens[i]; }
int getinttoken(unsigned int i) const { return atoi(tokens[i].c_str()); }
};

Parser::Parser(const char* filename) :
filename(filename),
linect(0)
{
filestream = ifstream(filename); // OK in VC++, not with GCC?
}

bool Parser::readline()
{
std::string line;
getline(filestream, line);
std::stringstream ss(line);
std::string token;

tokens.clear();
while(getline(ss, token, ' ')){ if(token != "") tokens.push_back(token); }
linect++;
return (filestream != NULL);
}

但是当我尝试用 GCC 4.8.2 编译它时,我收到错误消息说我无法分配给 filestream。根据我在本网站其他地方阅读的内容,您可以执行以下操作

std::ifstream filestream(filename);

但是你做不到

std::ifstream filestream;
filestream = ifstream(filename);

如果我想将 filestream 声明为 Parser 类的成员并在构造函数中对其进行初始化,这基本上就是我需要做的事情。

我希望将文件流保存在 Parser 类中,这样那些使用解析器的人就不需要声明和跟踪它了。在我看来,这应该是自包含在 Parser 类中,因为它的内部方法(例如 readline())是唯一使用它的方法。

有没有一种方法可以同时适用于两个平台?

谢谢。

编辑:我的修复是显式调用ifstreamopen() 方法。我的解析器类构造函数现在看起来像:

Parser::Parser(const char* filename) :
filename(filename),
linect(0)
{
filestream.open(filename);
// Do some checking to make sure the file exists, etc.
}

最佳答案

你不能,因为 std::ifstream 已经删除了复制构造函数和复制赋值。你可以通过做来绕过

filestream.swap(ifstream(filename)).

它在 visual studio 上编译的事实主要是因为它被内联到移动赋值或移动构造函数中(我不太好告诉你到底是哪个)。如果你尝试

std::ifstream myF;
filestream = myF;

它不会编译。

但是你可以尝试做我写的 Action ,或者你可以调用 .open( http://en.cppreference.com/w/cpp/io/basic_ifstream/open )

关于c++ - 如何将文件流作为类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24767957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com