Sha*_*fiz 27 c++ most-vexing-parse
我从这里得到了代码.
class Timer {
public:
Timer();
};
class TimeKeeper {
public:
TimeKeeper(const Timer& t);
int get_time()
{
return 1;
}
};
int main() {
TimeKeeper time_keeper(Timer());
return time_keeper.get_time();
}
Run Code Online (Sandbox Code Playgroud)
从它的外观来看,由于该行应该会出现编译错误:
TimeKeeper time_keeper(Timer());
Run Code Online (Sandbox Code Playgroud)
但只有在return time_keeper.get_time();
存在的情况下才会发生 .
为什么这条线甚至很重要,编译器会发现time_keeper(Timer() )
构造上的含糊不清.
Boa*_*niv 26
这是因为它TimeKeeper time_keeper(Timer());
被解释为函数声明而不是变量定义.这本身并不是错误,但是当您尝试访问get_time()
time_keeper 的成员(这是一个函数,而不是TimeKeeper实例)时,您的编译器会失败.
这是编译器查看代码的方式:
int main() {
// time_keeper gets interpreted as a function declaration with a function argument.
// This is definitely *not* what we expect, but from the compiler POV it's okay.
TimeKeeper time_keeper(Timer (*unnamed_fn_arg)());
// Compiler complains: time_keeper is function, how on earth do you expect me to call
// one of its members? It doesn't have member functions!
return time_keeper.get_time();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2436 次 |
最近记录: |