ifstream变量可以是全局变量吗?

Jef*_*her 2 c++ ifstream

// stream from file.
ifstream file;

int main (int argc, char * argv[]) {

// get argument passed from command line
// This is file name
if (argc != 2 ) {
    cout << "use:  ./executable <filename>";

}else {
    //cout << "You are using filename: " << argv[1];

    // start the file stream
    file (argv[1]);
}
Run Code Online (Sandbox Code Playgroud)

有什么理由file(argv[1])会给出错误吗?我可以将ifstream作为全局变量吗?

Mar*_*off 6

当你应该使用时,你试图调用ifstream()运算符(不存在)file.open(argv[1]).

除此之外,拥有全球性并非违法ifstream.