1.成员函数指针的用法
1 #include <iostream> 2 using namespace std; 3 class base 4 { 5 public: 6 int test(int lhs,int rhs) 7 { 8 cout<<"base test"<<endl; 9 return 1; 10 } 11 }; 12 class derived:public base 13 { 14 public: 15 int test(int lhs,int rhs) 16 { 17 cout<<"derived test"<<endl; 18 return 2; 19 } 20 }; 21 int main() 22 { 23 base *p; 24 derived d; 25 int (base::*baseFunction)(int,int); 26 int (derived::*derivedFunction)(int,int); 27 //基类指针指向子类对象+基类成员函数指针调用基类成员函数 28 p=&d; 29 baseFunction=&base::test; 30 (p->*baseFunction)(1,2);//相当于d.base::test(int,int); 31 //基类指针指向子类对象+基类成员函数指针调用子类成员函数 32 p=&d; 33 baseFunction=(int (base::*)(int,int))&derived::test; 34 (p->*baseFunction)(1,2);//相当于d.test(int,int); 35 return 0; 36 }
输出
base test
derived test
2.成员函数指针模拟多态
1 #include <iostream> 2 using namespace std; 3 class base 4 { 5 public: 6 base() 7 { 8 virtualFunctionPointer=&base::test; 9 } 10 ~base() 11 { 12 13 } 14 int (base::*virtualFunctionPointer)(); 15 16 int test() 17 { 18 //判断是否为基类实例,防止无限递归 19 if(virtualFunctionPointer==&base::test) 20 { 21 cout<<"base"<<endl; 22 return 1; 23 } 24 //子类对象通过基类指针调用test,多态 25 else 26 return (this->*virtualFunctionPointer)(); 27 28 } 29 30 }; 31 class derived:public base 32 { 33 public: 34 35 derived() 36 { 37 virtualFunctionPointer=(int (base::*)())&derived::test; 38 } 39 ~derived() 40 { 41 42 } 43 int test() 44 { 45 cout<<"derived"<<endl; 46 return 2; 47 } 48 49 }; 50 int main() 51 { 52 derived d; 53 base *p=&d; 54 cout<<p->test()<<endl; 55 base b; 56 p=&b; 57 cout<<p->test()<<endl; 58 59 return 0; 60 }
输出:
derived
2
base
1