如果将fstream声明为类的成员,如何实例化fstream? [英] How to instantiate an fstream if you declare it as a member of a class?

查看:174
本文介绍了如果将fstream声明为类的成员,如何实例化fstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What constructor can you use to instantiate an fstream if you declare it as a member of a class?

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

// allowed
std::fstream myFile;
}







// constructor
Foo::Foo() {
// what form of myFile("\\temp\\foo.txt", fstream::in | fstream::out | fstream::trunc)  can I use here?


myFile = ???
}


推荐答案

在新版本的C ++中(C ++ 11),那么上面的代码就可以了;

In the new version of C++ (C++11), then the above code you have is perfectly fine; initializations are allowed inside the body of a class.

在C ++ 03(C ++的早期版本)中,可以初始化 fstream 通过使用成员初始化程序列表,如下所示:

In C++03 (the previous version of C++), you can initialize the fstream by using the member initializer list like this:

Foo::Foo() : myFile("file-name", otherArguments) {
    // other initialization
}

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

Syntatically, this is done by adding a colon after the constructor name but before the brace, then listing the name of the field you want to initialize (here, myFile), and then in parentheses the arguments you want to use to initialize it. This will cause myFile to be initialized properly.

希望这会有所帮助!

这篇关于如果将fstream声明为类的成员,如何实例化fstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆