Most vexing parse confusion(最令人头疼的解析混乱)
问题描述
我正在学习 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.
这篇关于最令人头疼的解析混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最令人头疼的解析混乱
基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01