【问题标题】:Can an ifstream variable be a global variable?ifstream 变量可以是全局变量吗?
【发布时间】:2009-11-12 02:33:57
【问题描述】:
// 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 作为全局变量吗?

【问题讨论】:

    标签: c++ ifstream


    【解决方案1】:

    您正在尝试调用ifstream() 运算符(不存在),而您应该使用file.open(argv[1])

    除此之外,拥有一个全局 ifstream 并没有什么违法的。

    【讨论】:

    • 这是有道理的。我没有意识到我正在使用构造函数。感谢您的快速回复。
    • 其实他打电话给ifstream::operator() 不存在。
    【解决方案2】:

    您可以将 ifstream 作为全局变量(这是否是好的样式是另一个问题)。

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

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

    file.open( argv[1] );
    

    【讨论】:

    • 是的,我意识到使用全局变量并不是最好的主意。对于这个项目,这就足够了。感谢您的补充说明。
    猜你喜欢
    • 2017-04-26
    • 2019-08-26
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多