类中的 ifstream 变量

ifstream variable in class

本文关键字:变量 ifstream      更新时间:2023-10-16

我有我的类,里面必须有ifstream文件。

我不知道如何在类标题中呈现它

一个:

class MyClass
{
    ...
    ifstream file;
    ...
}

乙:

class MyClass
{
    ...
    ifstream& file;
    ...
}

我知道 ifstream 必须在十度中获取路径,那么我该怎么做呢?

另外,我如何使用它打开文件?

编辑:

想要第一种方法,但是我如何语法地使用它?

假设这是标题(它的一部分)

class MyClass
{
    string path;
    ifstream file;
public:
    MyClass();
    void read_from_file();
    bool is_file_open();
    ...

}

函数

void MyClass::read_from_file()
{
    //what do I do to open it???
    this->file.open(this->path); //Maybe, IDK
    ... // ?
}

您很可能想要第一个选项。第二个是对其他ifstream对象的引用,而不是属于MyClassifstream

您无需立即为ifstream提供路径。你可以稍后调用ifstreamopen函数并给它一个路径。但是,如果要在初始化时立即打开ifstream,则需要使用构造函数的初始化列表:

MyClass() : file("filename") { }

如果需要构造函数采用文件名,只需执行以下操作:

MyClass(std::string filename) : file(filename) { }

在构造函数中初始化它:

class my_class {
public:
    my_class(char const* path) : file(path) {
    }
    my_class(std::string const& path) : my_class(path.c_str()) {
    }
private:
    std::ifstream file;
};

另请参阅权威C++书籍指南和列表