C++虛函數與非虛函數的區別。

#include <iostream> #include <string> /* * Animal 與Dog之間沒有虛函數 * Animal Fish有一個eating的虛函數 * 通過"基類的指針" 訪問 子類(們)的成員函數。這叫動態多態。是用虛函數的技術完成的。這也叫動態綁定。] * 當我們使用基類的引用(或指針)調用一個虛函數時將發生動態綁定(dynamic binding) 因爲我們直到運行時才能知道到底調用了哪個版本的虛函數,可能是基類中的版本也可能是派生類中的版本,判斷的依據是引用(或指針)所綁 定的對象的真實類型。 * 與非虛函數在編譯時綁定不同,虛函數是在運行時選擇函數的版本,所以動態綁定也叫運行時綁定(run-time binding)。 * * 虛函數的指針會保存到class裏的"虛函數表"中。每一個對象都會一個自己的“虛函數表”。類似對函數指針列表。 * * */ using namespace::std; class Animal { public: string name; string attr; Animal(string n):name(n){}; Animal(string n,string a):name(n),attr(a){}; void runing(int i) { cout<<"animal("<<name <<") can runing "<<i<<" meter!"<<endl; } void moving() { cout<<"animal ("<<name <<")can moving !"<<endl; } virtual void eating() //虛函數。 { cout<<"animal ("<<name <<")must eat something!"<<endl; } }; class DOG: public Animal { public: #if 1 using Animal::Animal; //**這個特性叫繼承構造函數** 此句表示子類可以使用Animal類裏的所有構造函數,不需要程序員再手動定義一遍了,在此例中省去了如下代碼。 #else DOG(string t):Animal(t){}; DOG(string t,string x):Animal(t,x){}; #endif void runing(float f) { cout<<"dog run fast "<<f<<" meter!" <<endl; } void moving() { cout<<"dog move fast!"<<endl; } }; class Fish: public Animal { public: using Animal::Animal; void eating() { cout<<"fish eat in the water"<<endl; } }; /* * 由於moving不是虛函數,所以p->moving,使用了animal裏的 moving * */ void test_moving(class Animal *p) { p->moving(); } /* * eating在基類中是一個虛函數,所以test_eating的入參是animal類型,但在程序運行過程中 “動態地”找到真正的數據類型,並調用真正的方法函數。 * 這也是多態的一種方式。 * * */ void test_eating(class Animal* p) { p->eating(); } void test_eating_moving(class Animal& p) { p.eating();//是虛函數,在運行時動態來決定。 p.moving(); //moving不是虛函數,在編譯時,決定了它是animal的moving } int main(void) { class DOG dog("Dog bingo"); class Animal a("Common-Animal"); class Fish fish("Shark"); dog.moving(); a.moving(); cout<<"dog is test_moving"<<endl; test_moving(&dog); dog.runing(4.4); //這裏在編譯時dog.runing函數就已經是DOG類的runing函數了。 dog.runing(9);//int 9在這裏就被強制轉義成float 了。 cout<<"fish test eating"<<endl; test_eating(&fish); fish.runing(4);//由於 Fish類裏無runing函數,它在靜態編譯時使用了父類Animal的runing函數。 cout<<"-test_eating_moving(dog)----"<<endl; test_eating_moving(dog); cout<<"-test_eating_moving(fish)----"<<endl; test_eating_moving(fish); cout <<"----------------sizeof(dog),sizeof(animal)and sizeof(fish)"<<endl; cout<<"dog size:"<<sizeof(dog)<<endl; cout<<"animal size:"<<sizeof(a)<<endl; cout<<"class Fish size:"<<sizeof(class Fish)<<endl; cout <<"size=8, this is a virtial_function_table 's size, this table has only function point. so is 8"<<endl; return 0; }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章