为什么我无法在同一代码行中创建和打开ofstream?

gsa*_*ras 1 c++ oop fstream file ofstream

我可以:

std::ofstream outfile; outfile.open("foo");
Run Code Online (Sandbox Code Playgroud)

但不是:

std::ofstream outfile.open("foo");
Run Code Online (Sandbox Code Playgroud)

因为它给出了这个错误:

error: expected ';' at end of declaration
    std::ofstream outfile.open("foo");
                         ^
Run Code Online (Sandbox Code Playgroud)

你也可以在中看到Live Demo.

为什么?

PS:我知道我可以std::ofstream outfile("foo");,但我怀疑我错过了一个C++机制,这就是我要问的原因.

Swo*_*ish 8

为什么?

因为该语言不允许将声明与成员函数调用组合在一起.outfile在声明之后,变量甚至不存在.

使用构造函数打开文件:

std::ofstream outfile("foo");
Run Code Online (Sandbox Code Playgroud)

  • @gsamaras如果你已经了解了构造函数,而且我们都知道你这样做,我不明白为什么你问这个问题. (2认同)