指向成员的指针允许您引用类对象的非静态成员。不能使用指向成员的指针指向静态类成员,因为静态成员的地址不与任何特定对象相关联。若要指向静态类成员,必须使用普通指针。可以使用指向成员函数的指针,其方式与指向函数的指针相同。您可以比较指向成员函数的指针,为它们赋值,并使用它们来调用成员函数。请注意,成员函数的类型与非成员函数的类型不同,非成员函数具有相同的参数数量和类型以及相同的返回类型。可以声明和使用指向成员的指针,如以下示例所示:
//https://www.ibm.com/docs/en/i/7.4?topic=only-pointers-members-c
#include <iostream>
using namespace std;class X {
public:int a;void f(int b) {cout << "The value of b is "<< b << endl;}
};int main() {// declare pointer to data memberint X::*ptiptr = &X::a;// declare a pointer to member functionvoid (X::* ptfptr) (int) = &X::f;// create an object of class type XX xobject;// initialize data memberxobject.*ptiptr = 10;cout << "The value of a is " << xobject.*ptiptr << endl;// call member function(xobject.*ptfptr) (20);
}