c++ - 为什么它是指向 void 声明符的指针而不是指向成员函数的指针?

标签 c++ pointers declaration

我编写的以下非常简单的示例是为了实现指向成员概念的指针:

struct X
{
    void f();
};

void X::*g();//error: 'g' declared as a member pointer to void

int main(){
}

DEMO 正式地,标准说:

In a declaration T D where D 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 of D is “derived-declarator-type-list cv-qualifierseq pointer to member of class nested-name-specifier of type T”.

特别是在我的案例中,我们有:

D1g(),

Tvoid,

nested-name-specifier * attribute-specifier-seq_opt cv-qualifier-seqoptX::*

derived-declarator-type-list Tfuntion 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/

相关文章:

c++ - 使用 time() 函数计算执行时间

c++ - 使用具有特定搜索条件的 FindFirstFIleEx() 的示例

c++ - Uniform_real 不接受 numeric_limits::lowest()

c - 不同的指针是否被认为是不同的数据类型?

c++ - int (abc)(int,int) 是什么意思?

c++ - 以整数数组为参数并返回数组中奇数之和的函数

c - 在 C 中,指针和数组之间的算术如何工作?

c++ - 返回局部变量

C++,用define声明一个数组;怎么了? (简单快捷)

有人可以帮我用 C 语言进行此前向声明吗?