最烦琐的解析C ++ 11 [英] Most vexing parse C++11
问题描述
我很困惑关于 Y y {X {}};
这行是什么,什么是它与最烦琐的解析的连接。赞赏简短的说明:
#include< iostream>
struct X {
X(){std :: cout<< X; }
};
struct Y {
Y(const X& x){std :: cout< Y; }
void f(){std :: cout<< F; }
};
int main(){
Y y {X {}};
y.f();
}
>
它创建了一个临时 X
通过调用默认构造函数初始化它,然后使用它来初始化 Y
变量,调用 const X&
转换
如果您尝试使用旧式初始化语法写这个语句
Y y
那么所谓的最讨厌的解析会将此解释为函数,而不是变量,声明:一个名为 y
的函数,返回类型为 Y
和单个参数,其类型为a a)函数返回 X
。
您可以添加多余的括号,函数声明:
Y y((X()));
或者,因为C ++ 11,你可以使用括号初始化作为你的例子。 p>
I'm confused about Y y {X{}};
what exactly this line does and what is its connection to the most vexing parse. A brief explanation is appreciated:
#include <iostream>
struct X {
X() { std::cout << "X"; }
};
struct Y {
Y(const X &x) { std::cout << "Y"; }
void f() { std::cout << "f"; }
};
int main() {
Y y {X{}};
y.f();
}
what exactly this line does
It creates a temporary X
, value-initialising it by calling the default constructor, and then uses that to initialise a Y
variable, calling the const X&
conversion constructor.
where is connection to Most vexing parse
If you were to try to write this using old-school initialisation syntax
Y y (X());
then the so-called "most vexing parse" would interpret this as a function, rather than a variable, declaration: a function called y
, with return type Y
and a single parameter, whose type is a (pointer to a) function returning X
.
You could add extra parentheses, so that it can't be interpreted as a function declaration:
Y y ((X()));
or, since C++11, you can use brace-initialisation as your example does.
这篇关于最烦琐的解析C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!