C++ member function pointer

来源:互联网 发布:什么是云计算和大数据 编辑:程序博客网 时间:2024/04/28 18:06

//1.derived class can call the base class function, but the base class can not call the derived class function, member pointer can not do it
//2.c++ member function is strict
//3.the size of C++ pointer maybe not equal to the size of machine word

#include <stdio.h>#include <iostream>using namespace std;//1.0--------------------------------------------------------------------------------------//1.derived class can call the base class function, but the base class can not call the derived class function, member pointer can not do it//2.c++ member function is  strictclass base{  int a;public:  void hello()  {    cout<<"base hello\n";  }    void world()  {    cout<<"base world\n";  }  };class Derived1: public base{public:  void hello()  {    cout<<"Derived1 hello\n";  }  void call(Derived1 *b1, void (Derived1::*fun)())  {    (b1->*fun)();  }};class Derived2:public base{public:  void world()  {    cout<<"Derived2 world\n";  }};/*void call(base *b1, void (base::*fun)()) //can not work{  (b1->*fun)();}*/void call(Derived1 *b1, void (Derived1::*fun)()){  (b1->*fun)();}typedef void (Derived1::*pFun)(); //1.1--------------------------------------------------------------------------------------class BaseClass { public:      void BaseClassFun(int x, char *p) {       printf("In BaseClass\n"); };};class DerivedClass : public BaseClass { public:};//1.1--------------------------------------------------------------------------------------class CBase1 {};class CBase2 {};class CDerive2 : public CBase1, public CBase2 {};typedef void (CDerive2::*FPderive2)();int main() {    // Declare a member function pointer for BaseClass    typedef void (BaseClass::*m_f_p)(int, char *);    m_f_p memfunc_ptr;    memfunc_ptr = &DerivedClass::BaseClassFun;     DerivedClass *dc;    char pstr[]="";    ( dc->*memfunc_ptr)(1,pstr);//--------------------------------------------------------//3.the size of C++ pointer maybe not equal to the size of machine word         void (*pf)();    cout << "sizeDerive2 = " << sizeof(pf) << endl;       size_t sizeDerive2 = sizeof(FPderive2);    cout << "sizeDerive2 = " << sizeDerive2 << endl;//---------------------------------------------------------//  typedef void (base::*pFun)();   Derived1 d1;  Derived2 d2;    pFun pf1;  pf1=&Derived1::hello;  (&d1)->call(&d1,&Derived1::hello); // (&d1)->call(&d1,&Derived1::world);//  (&d1)->call(&d1,&base::hello);//  (&d1)->call(&d1,&base::world);    call(&d1,&base::world);    call(&d1,&Derived1::hello);  call(&d1,&Derived1::world);  call(&d1,&base::hello);  call(&d1,&base::world);      return 0;}
0 0
原创粉丝点击