使用類成員函數指針需要掌握的三點。
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);
- }