指向成員函式的指標

要訪問類的成員函式,你需要具有特定例項的控制代碼,作為例項本身或指標或對它的引用。給定一個類例項,如果你的語法正確,你可以使用指向成員的指標指向其各個成員! 當然,必須將指標宣告為與你指向的型別相同的型別…

typedef int Fn(int); // Fn is a type-of function that accepts an int and returns an int

class Class {
public:
    // Note that A() is of type 'Fn'
    int A(int a) { return 2*a; }
    // Note that B() is of type 'Fn'
    int B(int b) { return 3*b; }
}; // Class

int main() {
    Class c;          // Need a Class instance to play with
    Class *p = &c;    // Need a Class pointer to play with

    Fn Class::*fn;    // fn is a pointer to a type-of Fn within Class

    fn = &Class::A;   // fn now points to A within any Class
    (c.*fn)(5);       // Pass 5 to c's function A (via fn)
    fn = &Class::B;   // fn now points to B within any Class
    (p->*fn)(6);      // Pass 6 to c's (via p) function B (via fn)
} // main()

與指向成員變數的指標(在前面的示例中)不同,類例項和成員指標之間的關聯需要與括號緊密繫結,這看起來有點奇怪(好像 .*->*不夠奇怪!)