指向成员函数的指针

要访问类的成员函数,你需要具有特定实例的句柄,作为实例本身或指针或对它的引用。给定一个类实例,如果你的语法正确,你可以使用指向成员的指针指向其各个成员! 当然,必须将指针声明为与你指向的类型相同的类型…

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()

与指向成员变量的指针(在前面的示例中)不同,类实例和成员指针之间的关联需要与括号紧密绑定,这看起来有点奇怪(好像 .*->*不够奇怪!)