【问题标题】:ifstream variable in class类中的 ifstream 变量
【发布时间】:2013-12-21 15:01:02
【问题描述】:

我的班级必须有 ifstream 文件。

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

答:

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

乙:

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

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

还有如何用它打开文件?

编辑:

我想要第一种方式,但我该如何使用它的语法?

假设这是标题(部分)

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
    ... // ?
}

【问题讨论】:

    标签: c++ function class ifstream


    【解决方案1】:

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

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

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

    如果你需要构造函数来获取文件名,只需这样做:

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

    【讨论】:

    • 那么我该如何打开它,当它尝试 this->file.open 它给我错误
    • 您可以在构造函数中使用file.open("filename");,但最好使用初始化列表。
    • 但它是一个类,它不是一个常量文件
    • @user2410243 “常量文件”是什么意思?你只是问为什么没有this->?在大多数情况下,做this-> 是没有必要的;无论有没有它,它都可以工作。
    • 这不是我问的。当我使 ifstream 减速时 - 它在类中,并且应该通过我在构造函数中获得的路径。我得到了一个应该用它打开文件的路径。
    【解决方案2】:

    在构造函数中初始化它:

    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;
    };
    

    另见The Definitive C++ Book Guide and List

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 2012-04-15
      • 1970-01-01
      • 2018-09-09
      • 2011-01-10
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多