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.
这篇关于最令人头疼的解析混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最令人头疼的解析混乱
				
        
 
            
        基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 这个宏可以转换成函数吗? 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				