C ++,使用ifstream读取文件 [英] C++, reading a file using ifstream
问题描述
class Person {
private:
string firstName;
string lastName;
public:
Person() {}
Person(ifstream &fin) {
fin >> firstName >> lastName;
}
void print() {
cout << firstName
<< " "
<< lastName
<< endl;
}
};
int main() {
vector<Person> v;
ifstream fin("people.txt");
while (true) {
Person p(fin);
if (fin == NULL) { break; }
v.push_back(p);
}
for (size_t i = 0; i < v.size(); i++) {
v[i].print();
}
fin.close();
return 0;
}
请问您可以解释一下下面的代码片段如何工作?
if(fin == NULL){break; }
Please can you explain me, how following code snippet works? if (fin == NULL) { break; }
fin是堆栈上的一个对象,而不是一个指针,所以它不能变为NULL。
我在ifstream类中找不到重载的operator == function。
因此我无法理解此代码段的工作原理。
fin is a object on stack, not a pointer so it can not become NULL. I was unable to find overloaded operator== function in ifstream class. So I can not understand how this snippet works.
推荐答案
ifstream
类拥有 运算符void *()
(或C ++ 11中的 operator bool()
)。这是测试(fin == NULL)
时调用的。
The ifstream
class has an operator void *()
(or operator bool()
in C++11). This is what is called when you test (fin == NULL)
.
测试 fin == NULL
应该与测试 fin.fail()
完全相同。
Testing fin == NULL
should be exactly the same as testing fin.fail()
.
这篇关于C ++,使用ifstream读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!