作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下在 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()
)是唯一使用它的方法。
有没有一种方法可以同时适用于两个平台?
谢谢。
编辑:我的修复是显式调用ifstream
的open()
方法。我的解析器类构造函数现在看起来像:
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/
我是一名优秀的程序员,十分优秀!