指向成員的指針允許您引用類對象的非靜態成員。不能使用指向成員的指針指向靜態類成員,因為靜態成員的地址不與任何特定對象相關聯。若要指向靜態類成員,必須使用普通指針。可以使用指向成員函數的指針,其方式與指向函數的指針相同。您可以比較指向成員函數的指針,為它們賦值,并使用它們來調用成員函數。請注意,成員函數的類型與非成員函數的類型不同,非成員函數具有相同的參數數量和類型以及相同的返回類型。可以聲明和使用指向成員的指針,如以下示例所示:
//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);
}