使用类成员函数指针需要掌握的三点。
1) 申明类成员函数指针:::*
2) 通过对象指针调用类函数指针:->*
3) 通过对象调用类函数指针:.*
例:
/** 定义基类和子类 **/
class Base {
public:
virtual void print1() {
std::cout << "Base::print1()" << std::endl;
}
virtual void print2() {
std::cout << "Base::print2()" << std::endl;
}
};
class Derived : public Base {
public:
virtual void print1() {
std::cout << "Derived::print1()" << std::endl;
}
virtual void print2() {
std::cout << "Derived::print2()" << std::endl;
}
};
/**申明类成员函数指针类型 **/
typedef void (Base::*fn)();
/**通过对象指针调用类函数指针 **/
void test1(Base* obj, fn func) {
(obj->*func)();
}
/**通过对象调用类函数指针 **/
void test2(Base& obj, fn func) {
(obj.*func)();
}
void test_function_pointer() {
Base b;
Derived d;
test1(&b, &Base::print1);
test1(&b, &Base::print2);
test1(&d, &Base::print1);
test1(&d, &Base::print2);
test2(b, &Base::print2);
test2(d, &Base::print2);
}