#include <iostream>
using namespace std;
class Grandfather...{
public:
virtual void display()=0;
void run()...{
cout<<"Grandfather Run!!! ";
}
};
class Father:public Grandfather...{
public:
int fatherValue;
void display()...{
cout<<"Father Display!! ";
}
void run()...{
cout<<"Father Run!!! ";
}
};
class Uncle:public Grandfather...{
public:
int uncleValue;
void display()...{
cout<<"Uncle Display!! ";
}
void run()...{
cout<<"Uncle Run!!! ";
}
};
class Son:public Father...{
public:
int sonValue;
void display()...{
cout<<"Son Display!! ";
}
};
void main()...{
Grandfather* grandfather_pt=NULL;
Father* father_pt=NULL;
Son* son_pt=NULL;
Father father;
Uncle uncle;
Son son;
cout<<"靜态綁定 不用virtual關鍵字: ";
grandfather_pt=&uncle;
grandfather_pt->run();
grandfather_pt=&father;
grandfather_pt->run();
cout<<" 動态綁定 純虛函數: ";
grandfather_pt=&uncle;
grandfather_pt->display();
grandfather_pt=&father;
grandfather_pt->display();
cout<<" 指針強制轉換 ";
( (Father*)(&son) )->display();
// ( (Father*)(&son) )->run();
cout<<" 對象強制轉換 ";
((Father)son).display(); //隻允許upcasting,不允許downcasting
cout<<" 編譯器為了防止對象切割的發生,自動調用拷貝構造函數,是以,比較位址: ";
cout<<( father_pt=&((Father)son) )<<endl; //注意優先級
cout<<&son<<endl;
cout<<"發現二者不同! ";
}
輸出為:
靜态綁定 不用virtual關鍵字:
Grandfather Run!!!
Grandfather Run!!!
動态綁定 純虛函數:
Uncle Display!!
Father Display!!
指針強制轉換
Son Display!!
對象強制轉換 Father Display!!
編譯器為了防止對象切割的發生,自動調用拷貝構造函數,是以,比較位址:
//0012FDB8
//0012FE88
發現二者不同!
本文來自CSDN部落格,轉載請标明出處:http://blog.csdn.net/SearchLife/archive/2009/03/12/3985139.aspx