在'if'条件中定义fstream [英] Defining fstream inside a 'if' conditional

查看:171
本文介绍了在'if'条件中定义fstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

答案中,有以下代码:

if (std::ifstream input("input_file.txt"))
  ;

这似乎很方便,将'input'变量的范围限制在确认有效的范围内,然而VS2015和g ++似乎都没有编译它。它是某些编译器特定的东西还是需要一些额外的标志?

Which seems convenient, limiting the scope of the 'input' variable to where it's confirmed to be valid, however neither VS2015 nor g++ seems to compile it. Is it some compiler specific thing or does it require some extra flags?

在VS2015中,IDE突出显示std :: ifstream和input_file.txt以及最后的括号。 std :: ifstream标记为错误:此处不允许使用函数类型。

In VS2015 the IDE highlights "std::ifstream" and the "input_file.txt" as well as the last parentheses. "std::ifstream" is flagged with "Error: a function type is not allowed here".

VS2015 C ++编译器出现以下错误:

VS2015 C++ compiler gives following errors:


  • C4430缺少类型说明符 - 假设为int。注意:C ++不支持default-int

  • C2059语法错误:'('

推荐答案

你所拥有的代码是不合法的..在C ++ 11之前,if语句可以是

The code you have is not legal.. yet. Prior to C++11 a if statement could be

if(condition)
if(type name = initializer)

并且 name 将被评估为 bool 以确定条件。在C ++ 11/14中,规则用于允许

and name would be evaluated as a bool to determine the condition. In C++11/14 the rules expended to allow

if(condition)
if(type name = initializer)
if(type name{initializer})

其中, name 是在初始化以确定条件后评估为 bool

Where, again, name is evaluted as a bool after it is initialized to determine the condition.

从C ++ 17开始,尽管你会能够将if语句中的变量声明为复合语句,如for循环,允许您使用括号初始化变量。

Starting in C++17 though you will be able to declare a variable in a if statement as a compound statement like a for loop which allows you to initialize the variable with parentheses.

if (std::ifstream input("input_file.txt"); input.is_open())
{
    // do stuff with input
}
else
{
    // do other stuff with input
}

应该注意的是,这只是语法糖,上面的代码实际上已翻译成

It should be noted though that this is just syntactic sugar and the above code is actually translated to

{
    std::ifstream input("input_file.txt")
    if (input.is_open())
    {
        // do stuff with input
    }
    else
    {
        // do other stuff with input
    }
}

这篇关于在'if'条件中定义fstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆