如果将fstream声明为类的成员,如何实例化fstream?

lik*_*udo 9 c++ iostream

如果您将fstream声明为类的成员,您可以使用什么构造函数来实例化fstream?

#include <fstream>
class Foo {
Foo();
// not allowed
std::fstream myFile("\\temp\\foo.txt", fstream::in | fstream::out | fstream::trunc);

// allowed
std::fstream myFile;
}
Run Code Online (Sandbox Code Playgroud)
// constructor
Foo::Foo() {
// what form of myFile("\\temp\\foo.txt", fstream::in | fstream::out | fstream::trunc)  can I use here?


myFile = ???
}
Run Code Online (Sandbox Code Playgroud)

tem*_*def 7

在新版本的C++(C++ 11)中,您拥有的上述代码非常精细; 在类的主体内允许初始化.

在C++ 03(以前的C++版本)中,您可以fstream使用成员初始化列表初始化,如下所示:

Foo::Foo() : myFile("file-name", otherArguments) {
    // other initialization
}
Run Code Online (Sandbox Code Playgroud)

从语法上讲,这是通过在构造函数名称之后但在大括号之前添加冒号来完成的,然后列出要初始化的字段的名称(此处myFile),然后在括号中使用要用于初始化它的参数.这将导致myFile正确初始化.

希望这可以帮助!


yur*_*les 5

另一种选择是:

Foo::Foo () {
    myFile.open("\\temp\\foo.txt", fstream::in | fstream::out | fstream::trunc);

    if(!myFile.is_open()) {
        printf("myFile failed to open!");
    }

    //other initialization
}
Run Code Online (Sandbox Code Playgroud)