c++ - 最令人烦恼的解析困惑

标签 c++ class c++11 function-pointers

我正在学习 C++11,我偶然发现了统一初始化器。

我不明白下面应该显示“最令人烦恼的解析”歧义的代码:

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

您有一个类型为 Timer 的对象称为 dv正在从临时文件(= 符号右侧的表达式)进行复制初始化。

使用 auto 时要声明一个变量,该变量的类型与初始化它的表达式的类型相同——这里不考虑 cv 限定符和引用。

在您的例子中,初始化 dv 的表达式类型为 Timer ,等等 dv类型为 Timer .

这里:

int time_keeper(Timer());

您声明一个名为 time_keeper 的函数返回 int并将一个指针作为其输入,指向一个返回Timer的函数。并且不接受任何争论。

And why isn't the argument Timer (*) () ?

函数在作为参数传递时会衰减为指针,因此 time_keeper 的类型实际上是 int(Timer(*)()) .

为了说服自己,您可以尝试编译这个小程序:

#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!");
}

这是一个live example .

关于c++ - 最令人烦恼的解析困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51940170/

相关文章:

C++11模板错误信息: "cannot call member function without object"

c++ - 在 C++11 中,是否仍然需要传递对将接受函数输出的对象的引用?

c++ - 通过引用函数传递映射时出错

c++ - 我们什么时候应该将赋值运算符设为私有(private)而不是实现

python - 我如何从一个类访问另一个类?

java - Java中如何调用同一个类的方法?

c++ - 在qt中的gstreamer视频上覆盖小部件

c++ - 如何在 Windows 中从 C++ 程序打开 url?

c# - 类属性,在内部可获取和可设置,但只能在外部获取

c++ - 尖括号与圆括号中的非类型名称参数