2013-03-15 72 views
0

在「的內部C++對象模型」,作者給出的代碼,可能不夠明確下面的例子中,要求解析器向前看來解決它:這個C++表達式是如何解釋爲一個調用?

...if C++ were to throw off the C declaration syntax, lookahead would not be required to determine that the following is an invocation of pf rather than its definition:

// don’t know if declaration or invocation 
// until see the integer constant 1024 
int (*pf)(1024); 

他暗示,這被解釋爲調用的功能pf。我無法看到pf的聲明可能會成爲有效的調用。

+0

是的,我認爲作者在這裏犯了一個錯誤。 – 2013-03-15 11:00:31

+1

文字混淆。在重讀時,我認爲這意味着該行將是一個在沒有C語句syntax_的假設語言中的調用。 – MSalters 2013-03-15 11:24:50

回答

2

這就是所謂的pfint*的一個醜陋的聲明,其值爲1024。然而被初始化,這種轉換是無效的沒有一個明確的轉換:

int (*pf)((int*)1024); 

所以在問題中給出的行相當於:

int* pf = 1024; 

要理解爲什麼,認爲int ((((*pf))));int* pf;相同。您可以在宣言者周圍放置儘可能多的圓括號。

In a declaration T D where D has the form
(D1)
the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration
T D1
Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

我看不到任何理由,這將被視爲一個函數調用。特別是考慮到它從int開始。我可以看到它可能是一個函數指針的聲明,直到它看到整數文字。如果爲例,它已經成爲此:

int (*pf)(int); 

這將是類型的指針pf一份聲明,函數返回int並採取int類型的一個參數。

+0

這本書肯定意味着它是一個調用。這是一本相當老的書(它看起來像是在C++ 98之前的版本),所以也許這是不正確的。 – 2013-03-15 11:00:47

2

int (*pf)(int); - 這是申報

+0

這是不一樣的聲明。 – 2013-03-15 10:59:22

+0

當然不是。如果這是'pf'的聲明,那麼'int(* pf)(1024)'是一個有效的表達式。 – MSalters 2013-03-15 11:00:35

+0

@MSalters這是一個'pf'的重新聲明:「錯誤:''pf'有一個前面的聲明爲'int(* pf)(int)'」 – 2013-03-15 11:01:59

相關問題