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

时间:2009-11-12 02:33:57

标签: 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]);
}

file(argv[1])出错的原因吗?我可以将ifstream作为全局变量吗?

2 个答案:

答案 0 :(得分:6)

当您应该使用file.open(argv[1])时,您尝试拨打ifstream的{​​{1}}运营商(不存在)。

除此之外,拥有全局()

并不违法

答案 1 :(得分:2)

你可以将ifstream作为一个全局变量(这是一个好的风格是一个不同的问题)。

问题似乎是您尝试使用构造函数:file(argv[1])

此时已经构造了全局变量(使用默认构造函数),而您需要使用open方法。

file.open( argv[1] );