为什么在if条件中解析? [英] Why vexing parse in an if condition?

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

问题描述

考虑代码:

#include <iostream>

struct Foo
{
    Foo(int){}
    operator bool() const
    {
        return true;
    }
};

int main()
{
    if(Foo foo{42})
    {
        std::cout << "ok\n";
    }
}

它在gcc5下编译得很好。但是,如果我替换 if(Foo foo {42})

It compiles fine under gcc5. However, if I replace the line if(Foo foo{42}) with

if(Foo foo(42))



我得到一个编译时错误: p>

I get a compile-time error:


错误:'foo'之前的主要表达式

error: expected primary-expression before 'foo'

这里发生了什么?

推荐答案

条件的语法不包括经典的构造函数调用。

The syntax for a condition does not include classic constructor invocation.




     attribute-specifier- seq opt decl-specifier-seq declarator = initializer-clause

      attribute-specifier-seq opt decl-specifier-seq declarator braced-init-list

condition:
    expression
    attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
    attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

中使用开关 while do 。我很惊讶,现在发现它用于 switch 。我从来没有想过这是一个条件。

This is used in if, switch, while and do. I was surprised to now discover that it's used in switch. I never thought of that as a condition.

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

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