C++ 为什么这不是一个令人烦恼的解析?
基本上,这是关于最烦人的解析的后续。我可以理解,这是由于函数声明和变量定义之间存在歧义 但在科莫在线,我只是厌倦了以下内容C++ 为什么这不是一个令人烦恼的解析?,c++,most-vexing-parse,C++,Most Vexing Parse,基本上,这是关于最烦人的解析的后续。我可以理解,这是由于函数声明和变量定义之间存在歧义 但在科莫在线,我只是厌倦了以下内容 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
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.
}
但它编译得很好,没有错误。我查阅了标准文档,但无法得出一个推理
那么,我在这里遗漏了什么?10不能是参数类型名称,因此这必须是变量声明
编译器必须选择一个函数声明才能这样做,但在许多情况下它不能这样做,并且没有歧义。这不是一个令人烦恼的解析,因为您使用了整数文本,而不是,比如:
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;
}
#包括
结构T{int f(){return 1;}};
int main(int argc,字符**argv){
T(T());
std::cout,因为10
不是一种类型。:)
这将是一个非常麻烦的解析:
T myT(T());
// T() gets interpreted as function pointer argument to a function returning T();
// This is equivalent to:
T myT(T (*fn)());
另一种最令人烦恼的解析是:
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);
如果您正确地构造了T