成员函数指针的使用

    技术2022-05-20  40

    参考:

    1.http://www.tianya.cn/publicforum/content/it/1/256804.shtml

    2.http://bbs.bccn.net/thread-47699-1-1.html

     

    类中的成员函数指针的声明与使用方法,注:编译通过,但不知运行结果。

    //.h class CFos { public: CFos( CScanner & scanner, CList & list, CStore & store ); CStore & GetCell(); protected: private: CStore & ( CFos::* pFillStore )();//成员函数指针的声明,因为要指向的是本类的函数,因此要把这个指针限制为指向本类CFos函数的类型。 CStore & NullStore(); CStore & RegionStore(); CScanner & _scanner; CList & _list; CStore & _store; CShape::EType _type; }; //.cpp CFos::CFos( CScanner & scanner, CList & list, CStore & store ) :_scanner( scanner ), _list( list ), _store( store ) { _type = _shapeList[0]->Type(); switch( _type )//根据类型,使用不同的处理方法 { case CShape::_region: pFillStore = RegionStore; break; default: pFillStore = NullStore; } } CStore & CFos::GetCell() { return ( this->*pFillStore )();//函数指针成员的使用方法 } CStore & CFos::NullStore()//指针函数的具体实现1 { _store.SetUsable( false ); return _store; } CStore & CFos::RegionStore()//指针函数的具体实现2 { return _store; }


    摘录:

    构造一个指向成员的指针需要显式使用地址运算符&和限定名。从类的外部访问该类的成员需要范围解析运算符 (::) 和地址运算符&。生成下面的示例 C2475:  // C2475.cpp  #include <stdio.h>    struct A {   void f() {   printf("test");   }   void g();  };    void A::g() {   void (A::*p1)() = f; // ok in -Ze; error in -Za (C2475)   void (A::*p5)() = this->f; // C2475     // the following line shows how to call a function from outside the class   // void (A::*p4)() = &A::f;  }    int main() {   A *ap = new A;   A a;    void (A::*p5)() = a.f; // C2475     // the following line shows how to call a function from outside the class   void (A::*p4)() = &A::f;     // the following line shows how to call a member function   (ap->*p4)();   return 0;  }


    最新回复(0)