2011-05-08 106 views
3

基本上這是關於最令人頭疼的解析的this question的後續。我可以理解這是由於函數聲明和變量定義之間的不明確性。爲什麼這不是一個令人煩惱的解析?

但在Comeau在線,我只是厭倦了以下。

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. 
} 

但它編譯得很好,沒有錯誤。我研究了標準文檔,但無法推理。

那麼,我在這裏錯過了什麼?

+1

爲什麼你會想到什麼不同,你是正確的構建'T'的實例 – Nim 2011-05-08 08:15:08

回答

5

10不能是參數類型名稱,所以這必須是變量聲明。

編譯器必須選擇一個函數聲明,當它可以這樣做時,但在許多情況下,它不能也不存在歧義。

3

,因爲你用一個整數文字,而不是它是不是一個棘手的解析,說:

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; 
} 

這是不明確的,因爲這可能意味着:

  • myT是一個T用默認構造的初始化;或
  • myT是一個返回T並帶有T()類型的一個參數的函數,它表示一個零參數函數,其返回類型也是T

後一種解釋是默認的解釋,這就是爲什麼編譯器錯誤是因爲嘗試使用新聲明的函數而產生的,就好像它是您期望的對象一樣。

請參閱the Wikipedia article關於它。

6

因爲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); 
+0

是啊...... :)我愚蠢的... – liaK 2011-05-08 08:18:53