2013-03-15 37 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

相关问题