今天看了essential c++ 里面介绍了 Pointers to Class Member Function, 即成员函数指针后,有了浅薄的理解,在这里记录下来作为总结:
一般的函数指针(Pointer to Function) 和 成员函数指针(Pointer to Function) 的一个不同点: 前者必须通过同一类的对象加以调用,而该对象便是此成员函数内的this指针所指的对象。如:void (Test::*p)(int) = NULL; //指向 Test类 成员函数的指针
先贴代码:这个例子只是为了说明成员函数指针对用法。
#ifndef helloworld_ClassMemberPointer_h #define helloworld_ClassMemberPointer_h #include <assert.h> class Test{ typedef int (Test::*pOper)(int,int); public: static enum OPERATOR{ADD, SUB, MUL, DIV}; private: int sum(int a, int b) { return a+b; } int sub(int a, int b) { return a-b; } int mul(int a, int b) { return a*b; } int div(int a, int b) { assert( b!=0 ); return a/b; } public: static void setOperator( int type ) { oper = arrOper[type]; } int getResult(int a, int b) { return (this->*oper)(a,b); } private: static pOper arrOper[4]; static pOper oper ; }; Test::pOper Test::oper = &Test::sum; Test::pOper Test::arrOper[4] = {&Test::sum, &Test::sub, &Test::mul, &Test::div}; #endif
#include <iostream> #include "Test.h" using std::cout; using std::endl; int main(int argc, const char * argv[]) { Test test; Test::setOperator(Test::ADD); cout << test.getResult(3, 4) << endl; Test::setOperator(Test::SUB); cout << test.getResult(3, 4) << endl; Test test2; Test::setOperator(Test::MUL); cout << test2.getResult(3, 4) << endl; return 0; }
分析下Test 类:
类中
typedef int (Test::*pOper)(int,int)
static pOper arrOper[4]; static pOper oper ;以上等同于:
static int (Test::*arrOper[4])(int,int); static int (Test::*oper)(int,int);
Test test3; int (Test::*p)(int, int) = &Test::sum; int s = (test3.*p)(1, 2); cout << s << endl;这里要注意:文章刚开始有说到:指向类成员函数的指针必须通过同一类的对象加以调用,如上面用test3对象调用。这点是最容易和普通函数指针区分的。
暂时就只有这些浅薄的理解,至于具体怎么灵活应用它要靠以后实践了。