最令人烦恼的parsing
我从这里得到了代码。
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(); }
从它的外观来看,它应该得到编译错误,由于行:
TimeKeeper time_keeper(Timer());
但只有在return time_keeper.get_time();
存在。
为什么这一行甚至是重要的,编译器会在time_keeper(Timer() )
构造上time_keeper(Timer() )
歧义。
这是由于TimeKeeper time_keeper(Timer());
被解释为函数声明而不是variables定义。 这本身并不是错误,但是当您尝试访问time_keeper(这是一个函数,而不是TimeKeeper实例)的get_time()
成员时,编译器会失败。
这就是你的编译器如何查看代码:
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(); }