批註:多型例項

fdsafwagdagadg6576發表於2016-06-21
#include  <iostream>
#include <stdio.h>
using namespace std;
class Base
{
  public :
    virtual void Print() { cout<<"This is Base"<<endl;}
};
class Base2
{
  public:
    virtual void Print2() {cout <<"This is base2"<<endl;}
};
class Base3
{
  private :
    void Print3() {cout <<"This is base3"<<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();
  Base *p = new Base();
  pb->Print();
  int* pA = (int*)(*((int*)(pb+1)));
  int* pAB = (int*)(*((int*)pb));
  cout <<sizeof(Base)<<endl; //計算class的大小用sizeof(class), sizeof(物件)=指標大小,多大的類都等於8.
  cout <<sizeof(*pb)<<endl;    //在64bit機器上指標是8位元組。不同於32bit機器。
  cout <<sizeof(Derived)<<endl;  //在64bit機器上虛擬函式地址指標是8位元組。不同於32bit機器
  cout <<sizeof(Base3)<<endl;
  // it is the same as above
//  Func pFunc = (Func)*pA;
  int *a = (int*)pb;  //get Derive address
  int *b =((int*)pb+1);  //get Derive print2 address
  int c = *((int*)pb+1); //

  //d(*pA) is  save  Device print2 address

  //int *d = (int *)(*((int*)pb+1));

int *d = (int *)(*((int*)(pb+1))); //此處改成將(pb+1)闊起來,這樣+1就不是 int的4個位元組,而是pb的單位8個位元組了 . 非常漂亮!

   //cout <<"*a="<<*a<<endl;
   // cout <<"*b="<<*b<<endl;
   //it is the same as struct,add include function  point 
    cout<<"c="<<c<<endl;
 //   cout <<"*d="<<*d<<endl;
  Func pFunc =(Func)*pAB;
  pFunc();
  pFunc =(Func)*pA;
   //func point (void*)p
  //Func pFunc =(Func*)*pA;
  pFunc();
  return 0;
}

相關文章