函式指標呼叫

fdsafwagdagadg6576發表於2016-06-21
#include  <iostream>
using namespace std;
class Base
{
  public :
    virtual void Print() { cout<<"This is Base"<<endl;}
};
   // void PrintB() { cout<<"This is base printb"<<endl;}
class Base2
{
  public:
    virtual void Print2() {cout <<"This is base2"<<endl;}
};
class Derived: public Base,public Base2
{
  public:
    void Print() {cout<<"This is Derived"<<endl;}
    void Print2() {cout<<"This is Derived2"<<endl;}
    void Out() {cout<<"This should not be called"<<endl;}
};
typedef void (*Func)();
int main()
{
  Base *pb = new Derived();

 // Derived *db = new Derived();

  pb->Print();

//基類不能呼叫基類中沒有virutal的子類函式

 //pb->Out();

  //db->PrintB();

  int* pA = (int*)(*((int*)pb+1));

//將地址強制轉換成函式指標

  Func pFunc = (Func)*pA;

//呼叫地址即呼叫函式指標

  pFunc();
  return 0;
}

相關文章