3

基本上这是这个关于最令人烦恼的解析的问题的后续。我可以理解这是由于函数声明和变量定义之间的歧义。

但是在Comeau online,我只是厌倦了以下。

class T{

public:

    T(int i){
    }

    int fun1(){
        return 1;
    }

};

int main()
{
    T myT(10); // I thought it'd be a function declaration that takes an int and returns a type T
    myT.fun1(); // and a compiler error out here.
} 

但它编译得很好,没有错误。我查看了标准文档,但无法得出一个推理。

那么,我在这里缺少什么?

4

3 回答 3

7

因为10不是类型。:)

这将是一个最令人烦恼的解析:

T myT(T());
// T() gets interpreted as function pointer argument to a function returning T();
// This is equivalent to:
T myT(T (*fn)());

另一种最令人烦恼的 Parse 是这个:

unsigned char c = 42;
T myT(int(c));
// int(c) gets interpreted as an int argument called c.
// This is equivalent to:
T myT(int c);
于 2011-05-08T08:15:30.913 回答
6

10不能是参数类型名称,所以这必须是变量声明。

当编译器可以这样做时,它必须选择一个函数声明,但在许多情况下,它不能并且没有歧义。

于 2011-05-08T08:15:03.530 回答
3

这不是一个令人烦恼的解析,因为您使用的是整数文字,而不是说:

T myT(T());

就像在这个完整的例子中一样:

#include <iostream>

struct T { int f() { return 1; } };

int main(int argc, char** argv) {
    T t(T());
    std::cout << t.f() << '\n';
    return 0;
}

这是模棱两可的,因为它可能意味着:

  • myTT用默认构造初始化的T;或者
  • myT是一个返回 aT并接受一个类型参数的T()函数,它表示一个返回类型也是 的零参数函数T

后一种解释是默认解释,这就是为什么尝试使用新声明的函数时会导致编译器错误的原因,就好像它是您期望的对象一样。

请参阅有关它的 Wikipedia 文章

于 2011-05-08T08:15:21.470 回答