不清楚最令人讨厌的解析 [英] Unclear most vexing parse
问题描述
让我们假设以下类为Foo。
struct Foo
{
int i;
};
如果我想创建此类的实例并对其进行初始化,我应该这样做: Foo foo1 = Foo();
调用构造函数。
int main(void )
{
foo1 = Foo();
cout<< foo1.i<< :<< foo1.j<<恩德尔// 0
}
然后我以为我会使用以下行,但不是:
int main(void)
{
Foo foo2( ); //最令人讨厌的解析
cout<< foo2<<恩德尔// 1 ???为什么?
foo2.i ++; //错误:在'foo2'中请求成员'i',该成员是非类类型'Foo()'
}
为什么foo2初始化为int(1)而不是Foo()?
我最了解烦人的解析,它告诉我,根据我的理解,当一行可以解释为一个函数时,它将被解释为一个函数。
但是foo1()被解释为
Foo foo2()行之所以编译是因为它被解释为函数原型。好的。
为什么此行编译? cout<< foo2<< endl;
是否打印foo2函数的地址?
Foo foo2();
是一个函数声明。对于 cout<< foo2
, foo2
会衰减为函数指针,然后隐式转换为 bool
。作为非空函数指针,转换后的结果为 true
。 不使用 boolalpha
, std :: basic_ostream< CharT,Traits> :: operator<<
输出 1
true
。
如果boolalpha == 0,则将v转换为int类型,执行整数输出。
使用 std :: boolalpha
。
cout<< boolalpha<< foo2<<恩德尔//打印 true
Let's assume the following class Foo.
struct Foo
{
int i;
};
if I want to make an instance of this class and initialize it, I should do: Foo foo1 = Foo();
to call the constructor.
int main(void)
{
foo1 = Foo();
cout << foo1.i << " : " << foo1.j << endl; // " 0 "
}
then I thought I'd call the default constructor with the following line but it doesn't:
int main(void)
{
Foo foo2(); // most vexing parse
cout << foo2 << endl; // " 1 " ??? why?
foo2.i++; // error: request for member ‘i’ in ‘foo2’, which is of non-class type ‘Foo()’
}
Why is foo2 initialized to int(1) and not Foo()?
I know about the most vexing parse, it tells that, from my understanding, when a line can be interpreted as a function, it is interpreted as a function.
But foo1() is interpreted as an int, not a function, nor a Foo class.
The line Foo foo2() compiles because it is interpreted as a function prototype. OK.
Why does this line compiles? cout << foo2 << endl;
Does it print the address of the foo2 function?
As you said, Foo foo2();
is a function declaration. For cout << foo2
, foo2
would decay to function pointer, and then converts to bool
implicitly. As a non-null function pointer, the converted result is true
.
Without using boolalpha
, the std::basic_ostream<CharT,Traits>::operator<<
would output 1
for true
.
If boolalpha == 0, then converts v to type int and performs integer output.
You can see it more clearer with usage of std::boolalpha
.
cout << boolalpha << foo2 << endl; // print out "true"
这篇关于不清楚最令人讨厌的解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!