問題描述
我正在學習 C++11,我偶然發現了統一初始化程序.
I'm studying C++11 and I stumbled upon uniform initializers.
我不明白以下應該顯示最令人煩惱的解析"歧義的代碼:
I don't understand the following code which should show the "most vexing parse" ambiguity:
#include<iostream>
class Timer
{
public:
Timer() {}
};
int main()
{
auto dv = Timer(); // What is Timer() ? And what type is dv?
int time_keeper(Timer()); // This is a function right? And why isn't the argument " Timer (*) ()" ?
return 0;
}
推薦答案
這里:
auto dv = Timer();
您有一個名為 dv
的 Timer
類型的對象,它正在從臨時對象(=
右側的表達式)復制初始化代碼> 符號).
You have an object of type Timer
called dv
that is being copy-initialized from a temporary (the expression on the right side of the =
sign).
當使用 auto
聲明一個變量時,該變量的類型與初始化它的表達式的類型相同——這里不考慮 cv 限定符和引用.
When using auto
to declare a variable, the type of that variable is the same as the type of the expression that initializes it - not considering cv-qualifiers and references here.
在您的情況下,初始化 dv
的表達式的類型為 Timer
,因此 dv
的類型為 Timer
.
In your case, the expression that initializes dv
has type Timer
, and so dv
has type Timer
.
這里:
int time_keeper(Timer());
您聲明了一個名為 time_keeper
的函數,它返回一個 int
并將指針作為它的輸入,該函數返回一個 定時器
,不帶參數.
You declare a function called time_keeper
that returns an int
and takes as its input a pointer to a function which returns a Timer
and takes no argument.
為什么不是參數 Timer (*) ()
?
當作為參數傳遞時,函數衰減為指針,所以time_keeper
的類型實際上是int(Timer(*)())
.
Functions decay to pointers when passed as an argument, so the type of time_keeper
is actually int(Timer(*)())
.
為了說服自己,你可以嘗試編譯這個小程序:
To convince yourself, you could try compiling this little program:
#include <type_traits>
struct Timer { };
int main()
{
int time_keeper(Timer());
static_assert(
std::is_same<
decltype(time_keeper),
int(Timer(*)())
>::value,
"This should not fire!");
}
這里有一個referar">noliver>>.
Here is a live example.
這篇關于最令人頭疼的解析混亂的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!