继承自ifstream

use*_*271 4 c++ inheritance ifstream

我可以从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;
}
Run Code Online (Sandbox Code Playgroud)

我希望它能读取整个文件,但它只读取一个符号(这不是给定文件的第一个符号)......

bdo*_*lan 7

不要从ifstream继承.如果您需要更改输入流的行为,请继承streambuf,然后istream围绕它构建一个.如果您只想添加帮助器,请将它们设置为全局,以便您可以在任何istream上使用它们.

也就是说,你的bug在File构造函数中:

File::File(const char *fname, openmode mode)
{
    ifstream(fname, mode);
}
Run Code Online (Sandbox Code Playgroud)

这构造了一个(未命名的)ifstream,然后立即关闭它.你想调用超类构造函数:

File::File(const char *fname, openmode mode)
  : ifstream(fname, mode);
{

}
Run Code Online (Sandbox Code Playgroud)