2011-05-08 83 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