一、函数指针——基本形式
char Fun(int n) { return char(n); } //char(*pFun)(int); void main() { char(*pFun)(int); pFun = Fun; char c = (*pFun)(83); cout << c; }
二、函数指针——typedef形式
char Fun(int n) { return char(n); } //typedef char(*PFun)(int); //PFun pFun; void main() { typedef char(*PFun)(int); PFun pFun; pFun = Fun; char c = (*pFun)(83); cout << c; }
三、类成员函数指针
class Base { public: char Fun(int n) { return char(n); } }; //typedef char (Base::*PFun)(int); //PFun pFun; void main() { typedef char (Base::*PFun)(int); PFun pFun; pFun = &Base::Fun; Base instance; char c = (instance.*pFun)(83); cout << c; }
四、类成员函数指针——类指针
class Base { public: char Fun(int n) { return char(n); } }; //typedef char (Base::*PFun)(int); //PFun pFun; void main() { typedef char (Base::*PFun)(int); PFun pFun; pFun = &Base::Fun; Base *pInstance = new Base(); char c = (pInstance->*pFun)(83); delete pInstance; cout << c; }
五、类成员函数指针——内部调用(this->*)
class Base { public: char Fun(int n) { return char(n); } char Fun2() { char (Base::*pFun)(int); pFun = &Base::Fun; char c = (this->*pFun)(83); return c; } }; void main() { Base instance; char c = instance.Fun2(); cout << c; }
六、类成员函数指针——继承调用
class Base { public: char Fun(int n) { return char(n); } char Fun2(int n) { //char (Base::*pFun)(int); //pFun = &Base::Fun; typedef char (Base::*PFun)(int); PFun pFun = &Base::Fun; return Proc(n, pFun); } char Proc(int n, char(Base::*pFun)(int)) { return (this->*pFun)(n); } }; class Derive : Base { public: char Fun(int n) { return char(n - 1); } char Fun2(int n) { typedef char (Base::*PFun)(int); PFun pFun = static_cast<PFun>(&Derive::Fun); return Proc(n, pFun); } }; void main() { Base base; char bc = base.Fun2(83); cout << bc; Derive derive; char dc = derive.Fun2(83); cout << dc; }
七、类成员函数指针——虚拟函数
class Base { public: void OFun() { cout << "base ordinary" << endl; } virtual void VFun(int i) { cout << "base virtual" << endl; } }; class Derive : public Base { public: void OFun() { cout << "derive ordinary" << endl; } virtual void VFun(int i) { cout << "derive virtual" << endl; } }; void main() { typedef void (Base::*BaseOFun)(); typedef void (Derive::*DeriveOFun)(); BaseOFun baseOFun = &Base::OFun; DeriveOFun deriveOFun = static_cast<DeriveOFun>(baseOFun); typedef void (Base::*BaseVFun)(int); typedef void (Derive::*DeriveVFun)(int); BaseVFun baseVFun = &Base::VFun; DeriveVFun deriveFVun = static_cast<DeriveVFun>(baseVFun); Base base; (base.*baseOFun)(); (base.*baseVFun)(1); Derive derive; (derive.*deriveOFun)(); (derive.*deriveFVun)(1); }