最令人头疼的解析混乱

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();

您有一个名为 dvTimer 类型的对象,它正在从临时对象(= 右侧的表达式)复制初始化代码> 符号).

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.

这篇关于最令人头疼的解析混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)