【发布时间】:2011-01-24 09:39:07
【问题描述】:
我可以像这样从 ifstream 继承并从派生类中读取文件吗:
#include <iostream>
using namespace std;
const string usage_str = "Usage: extract <file>";
class File: public ifstream
{
public:
explicit File(const char *fname, openmode mode = in);
void extract(ostream& o);
};
File::File(const char *fname, openmode mode)
{
ifstream(fname, mode);
}
void File::extract(ostream& o)
{
char ch;
char buf[512];
int i = 0;
while (good()) {
getline(buf, sizeof(buf));
o<<buf;
i++;
}
cout<<"Done "<<i<<" times"<<endl;
}
void msg_exit(ostream& o, const string& msg, int exit_code)
{
o<<msg<<endl;
exit(exit_code);
}
int do_extract(int argc, char *argv[])
{
cout<<"Opening "<<argv[1]<<endl;
File f(argv[1]);
if (! f)
msg_exit(cerr, usage_str, 1);
f.extract(cout);
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 2)
msg_exit(cout, usage_str, 0);
do_extract(argc, argv);
return 0;
}
我希望它读取整个文件,但它只读取一个符号(这不是给定文件的第一个符号)...
【问题讨论】:
-
好()!那有什么作用?
-
ifstream(fname, mode)应该移动到初始化列表。您应该在尝试读取数据和使用数据之间进行一些错误检查,而不是仅在该过程的迭代之间进行。 -
这可能会有所帮助:stackoverflow.com/questions/772355/…
-
在这种情况下,我更喜欢聚合而不是继承,您仍然可以使用这些方法,而不必担心 ifstream 实际做了什么。
标签: c++ inheritance ifstream