使用fstream构造函数和open函数的区别

The difference between using fstream constructor and open function

我有一个关于 fstream 的构造函数和 .open 函数的简单问题。 下面两个表达式有区别吗?

1

fstream("file.txt",ios::app);

2

fstream fin;
fin.open("file.txt",ios::app);

对于(1),我不需要再次使用.open 函数,对吧?这两个表达式之间有什么功能上的区别吗?

我的第二个问题是,如果我将 openmode 留空,默认的打开模式是什么?

不,那里没有区别。

For (1), I don't need to use .open function again right?

没错。

Any functional differences between the two expression?

想不到

My second question is that if I left the openmode empty, what will be the default open mode?

ios_base::in|ios_base::out。有关详细信息,请参阅 http://en.cppreference.com/w/cpp/io/basic_fstream/open

您的两个代码段后面的对象状态没有差异。

为什么会有两个版本?

  1. 构造函数的存在是为了创建 fstream 与流直接关联的对象。

  2. 存在open是因为这些类型的对象无法复制。因此,您不能通过以下方式将 fstream 对象分配给不同的流:

    fstream foo('bblskd');
    // ...
    foo = fstream('skdjf');
    

(请注意,此接口是在移动语义之前设计的)。


可以找到默认的打开方式here

这是一个非常古老的问题,但 none 的答案在我看来是正确的。

两个版本相同。但是单独打开的原因是当您想创建自己的 class 继承自 basic_fstream 时。并且您想在 and/or 之后对构造函数的输入做一些事情。

class MoleStream : public std::basic_fstream<char> {
public:
    MoleStream () : std::basic_fstream<char> ("defaultmole") { }

    MoleStream ( const char *fn ) {
        std::string s = fn; s+=".mole";
        std::basic_fstream<char>::open (s);
        if ( !is_open() )
            std::basic_fstream<char>::open (fn);
    }
};

第二个 MoleStream 构造函数在打开之前和之后做一些事情。这在 C++ 中可能不是很好的做法,但它可能很有用。