2011-05-08 44 views
24

我从here得到的代码。最令人头疼的解析

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())构造中发现模糊性。

+0

的可能重复(http://stackoverflow.com/questions/3810570/why-is-没有调用的构造函数) – Mark 2013-03-08 18:55:30

回答

24

这是由于TimeKeeper time_keeper(Timer());被解释为函数声明而不是变量定义。这本身并不是错误,但当您尝试访问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(); 
} 
+0

虽然我知道在§13.1/ 3中的标准说,在这种情况下Timer函数类型被调整为函数类型的指针,但为什么有人希望它是调整为开始?在我看来,§13.1/ 3创造了整个“最棘手的解析”问题? – 2014-02-06 02:35:54