简体   繁体   English

指向函数作为结构中的静态成员的指针

[英]pointer to function as static member in structure

struct X {
   int f(int);
   static int f(long);
};

int (X::*p1)(int) = &X::f; // OK
int (*p2)(int) = &X::f; // error: mismatch
int (*p3)(long) = &X::f; // OK
int (X::*p4)(long) = &X::f; // error: mismatch
int (X::*p5)(int) = &(X::f); // error: wrong syntax for pointer to member
int (*p6)(long) = &(X::f); // OK

I think that p1 and p5 is the same case. 我认为p1和p5是相同的情况。 Why is p5 wrong? 为什么p5错了?

Because the standard says so. 因为标准是这样说的。 From the N3936: 来自N3936:

5.3.1 Unary operators 5.3.1一元运算符

  1. A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses . 仅当使用显式&时,才会形成指向成员的指针,并且其操作数是未括在括号中的qualified-id [ Note: that is, the expression &(qualified-id), where the qualified-id is enclosed in parentheses, does not form an expression of type “pointer to member.” Neither does qualified-id, because there is no implicit conversion from a qualified-id for a non-static member function to the type “pointer to member function” as there is from an lvalue of function type to the type “pointer to function” (4.3). [注意:也就是说,表达式&(qualified-id),其中qualified-id括在括号中,不形成“指向成员的指针”类型的表达式。也不是qualified-id,因为没有隐式转换从非静态成员函数的限定id到类型“指向成员函数的指针”类型,因为从函数类型的左值到类型“指向函数的指针”(4.3)。 Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id's class. 即使在unqualified-id类的范围内,也不是&nonqualified-id指向成员的指针。 — end note ] - 结束说明]

The C++ Standard's definition of the built-in operator & states that only when the parameter to & is a qualified-id , meaning something like Class::Member , does & result in a pointer-to-member. 的C ++标准的定义,内置operator &规定,只有当该参数&是一个合格的-ID,这意味着像Class::Member ,并&导致指针到成员。 The parentheses make it no longer a qualified-id , so it attempts to parse X::f directly, which is illegal in this context: you're assigning an int (*)(long) to an int (X::*)(int) . 括号使它不再是qualified-id ,所以它试图直接解析X::f ,这在这个上下文中是非法的:你将int (*)(long) int (X::*)(int)

The distinction between the two cases resolves an ambiguity. 两种情况之间的区别解决了模糊性。 Let's say that you have: 让我们说你有:

struct X {
    int m;
};
struct Y {
    int m;
};
struct Z : X, Y {
    void F();
};

void Z::F() {
    int X::*p1 = &X::m;
    int *p2 = &(X::m);
}

Here, &X::m is a pointer-to-member, whereas &(X::m) is an ordinary pointer to int , using the X:: qualification to resolve the ambiguity between X 's m and Y 's m . 这里, &X::m是指向成员的指针,而&(X::m)是指向int的普通指针,使用X::限定来解决XmYm之间的歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM