从成员函数中的构造函数中使用变量
我有以下类,它有一个构造函数,它读入一个txt文件,该文件包含构造函数应该创建的大小object
。然后我需要函数read()
来获取构造函数停止的位置,但由于某种原因,它再次从文件顶部开始。这是如何修复的?从成员函数中的构造函数中使用变量
class Reader {
public:
Reader(const char* file): _file(file) {
_ptr = 0;
ifstream _file(file);
_file >> word;
if(word!="BEGIN") {
//Raise error.
}
_file >> word; //Reads in next word.
if(word=="SIZE") {
_file >> size_x;
_file >> size_y;
_ptr = new Object(size_x,size_y);
}
else {
//Raise error.
}
_file >> word;
while(word=="POSITION") {
int readoutID;
int ix;
int iy;
_file >> readoutID >> ix >> iy;
//Set ID to position
_file >> word;
}
std::cout << "End of definition: " << word << std::endl;
}
bool read(){
std::cout << word << std::endl; // This word should be the one where the constructor stopped.
//Returns False at the end if file.
}
private:
Object* _ptr;
std::ifstream _file;
std::string word;
我的主要文件是这样的:
int main(){
Reader r("file.dat");
while(r.read()) {
//Function that prints out the values of read()
}
}
从你的问题我需要的函数read()拿起构造停止的地方,但由于某些原因,它开始于顶部该文件再次:您没有使用this->_file
但您创建一个本地变量_file
。因此,this->_file
的状态与打开时的状态相同:文件开始。
此外,构造函数没有正确命名(CaloReader
而不是Reader
)。
CaloReader(const char* file): _file(file) {
_ptr = 0;
ifstream _file(file); // local variable
_file >> word;
我该如何使用'this - > _ file'? –
你在学习C++吗? 'this - > _ file'只是表示你正在使用_file属性。您也可以简单地删除变量声明(如我的答案中所示)。然而,看到你的需要,你需要移除在构造函数外面读取单词的代码:它必须在读取方法中进行。 – NoDataFound
'_file'是有状态的。您应该继续停止构造函数以自动读取。这不适合你吗? –
你如何调用'read()'?和你的构造函数有什么关系 – xander
我有一个小的主文件,它首先创建一个'Reader'类的对象,然后我调用'read()'函数。请参阅编辑。 –