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++机制,这就是我要问的原因.
为什么?
因为该语言不允许将声明与成员函数调用组合在一起.outfile在声明之后,变量甚至不存在.
使用构造函数打开文件:
std::ofstream outfile("foo");
Run Code Online (Sandbox Code Playgroud)