我编写的以下非常简单的示例是为了实现指向成员概念的指针:
struct X
{
void f();
};
void X::*g();//error: 'g' declared as a member pointer to void
int main(){
}
DEMO 正式地,标准说:
In a declaration
T D
whereD
has the form
nested-name-specifier * attribute-specifier-seq_opt cv-qualifier-seqopt D1
and the nested-name-specifier denotes a class, and the type of the identifier in the declaration
T D1
is “derived-declarator-type-list T
”, then the type of the identifier ofD
is “derived-declarator-type-list cv-qualifierseq pointer to member of class nested-name-specifier of typeT
”.
特别是在我的案例中,我们有:
D1
是 g()
,
T
为 void
,
nested-name-specifier * attribute-specifier-seq_opt cv-qualifier-seqopt
是 X::*
derived-declarator-type-list T
是 funtion returned void
因此声明 T D 必须引入一个指向类 X 返回 void 的成员的函数指针
。
我哪里错了?
最佳答案
通过假设 g
首先与 ()
绑定(bind),您可以正确地开始推导,从而得到 g()
。但仅此一点就意味着 g
是一个函数,它不带参数,也不是指针。在这一点上,g
成为指针 的所有机会都永远消失了。声明的其余部分将描述函数的返回类型。所以,很明显,你的推导是不正确的。 (如果继续推导,您将得到错误消息中指定的类型)。
与运算符类似,声明的后缀部分比前缀部分具有更高的优先级。这意味着如果您希望您的 g
成为任何类型的指针,您必须首先强制您的 g
绑定(bind)到 *
。这是通过使用 ()
实现的:(*g)
。这将使 g
成为指向某物的常规指针。如果您希望 g
具有指向成员的指针 类型,则必须将整个 X::*
括在括号中:(X::*g)
。
最后,为了完成声明,我们将其设为返回 void
的指向成员函数的指针:void (X::*g)()
。
关于c++ - 为什么它是指向 void 声明符的指针而不是指向成员函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26052250/