注册 登录
编程论坛 C++教室

求助一个constructor和deconstructor的问题

winglesswu 发布于 2013-06-25 10:51, 580 次点击
要求写一个constructor和deconstructor,分别是:
1 ISBNPrefix(const char* filename) 这个函数接收一个包含一个文件名的字符串,该constructor仅打开文件
a one-argument constructor that receives a C-style, null-terminated string containing the name of a file that holds the prefix table
 ISBNPrefix(const char* filename);
This constructor opens the file for read only access.
2 deconstructor的要求是:
a destructor that cleans up before the current object goes out of scope
 ~ISBNPrefix();

如果class里的变量是普通变量,我知道怎么写,但是这个变量是指针,我就有点不明白了。我的代码分别是:
1 ISBNPrefix::ISBNPrefix(const char* filename)
    {
        FILE *fp;
        if (fp!=NULL)
            fp=fopen(filename, "r");
        else
            fp=NULL;
    }
2 ISBNPrefix::~ISBNPrefix()
    {
        if (fp!=NULL)
        fclose(fp);
        else
            fp=NULL;
    }
请知道的朋友指点一下,谢谢。
2 回复
#2
rjsp2013-06-25 11:21
基础知识还是要看点书的。差不多是这样:

struct ISBNPrefix
{
    ISBNPrefix(const char* filename) : file(filename)
    {
    }

    ~ISBNPrefix()
    {
        file.close();
    }

    std::ifstream file;
};
#3
wk1235862013-06-25 12:01
1