1. Usage of member function pointers
1#include <iostream>2 using namespacestd;3 class Base4 {5 Public:6 intTestintLhsintRHS)7 {8cout<<"Base Test"<<Endl;9 return 1;Ten } One }; A classDerived Public Base - { - Public: the intTestintLhsintRHS) - { -cout<<"derived Test"<<Endl; - return 2; + } - }; + intMain () A { at Base*p; - derived D; - int(Base::* basefunction) (int,int); - int(derived::* derivedfunction) (int,int); - //base class pointer to child class object + base class member function pointer call base class member function -p=&D; inbasefunction=&Base:: Test; -(p->*basefunction) (1,2);//equivalent to D.base::test (int,int); to //base class pointer to subclass Object + base class member function pointer call child class member function +p=&D; -Basefunction= (int(Base::*)(int,int)) &derived::test; the(p->*basefunction) (1,2);//equivalent to D.test (int,int); * return 0; $}
Output
Base Test
Derived test
2. member function pointer simulation polymorphism
1#include <iostream>2 using namespacestd;3 class Base4 {5 Public:6 Base()7 {8virtualfunctionpointer=&Base:: Test;9 }Ten~Base() One { A - } - int(Base::*virtualfunctionpointer) (); the - intTest () - { - //determines whether a base class instance prevents infinite recursion + if(virtualfunctionpointer==&Base:: Test) - { +cout<<"Base"<<Endl; A return 1; at } - //the subclass object calls test through a base-class pointer, polymorphic - Else - return( This->*virtualfunctionpointer) (); - - } in - }; to classDerived Public Base + { - Public: the * derived () $ {Panax NotoginsengVirtualfunctionpointer= (int(Base::*) ()) &derived::test; - } the~derived () + { A the } + intTest () - { $cout<<"derived"<<Endl; $ return 2; - } - the }; - intMain ()Wuyi { the derived D; - Base*p=&D; WuCout<<p->test () <<Endl; - Baseb; Aboutp=&b; $Cout<<p->test () <<Endl; - - return 0; -}
Output:
Derived
2
Base
1
Using member function pointers to simulate polymorphism in C + +