c++虛函數經典例子演示


c++博大精深,封裝,繼承,多態是c++的三大特征,c++很強大,但是強大的東西理解起來就是要比不強大的難一點,所以現在看看

c++的多態:

多態條件:

1.必須是公有繼承。

2.必須是虛函數

一個好的程序要對修改封閉,對擴展開放,虛函數就能很好的解決這個問題,

基類的指針指向子類的對象並調用子類的同名函數,要實現這種效果,就得用虛函數

關鍵字:virtual 

虛函數的注意點:

1.必須是普通成員函數(可以是常成員,不能是靜態成員,不能使全局函數)

2.內聯函數不會是虛函數

3.構造函數不能為虛函數(析構函數一般聲明為為虛函數)

經典例子:

 1 #include <iostream>
 2 
 3 using std::cout;
 4 using std::cin;
 5 using std::endl;
 6 
 7 // 基類
 8 class Fruit{
 9 public:
10     virtual void print(){
11         cout<< "Fruit" <<endl;
12     }
13 };
14 
15 class Banana: public Fruit{    // 一定要共有繼承
16 public:
17     void print(){            // 此處可省略virtual關鍵字,但是函數原型要與Fruit中虛函數 void print(); 完全一致
18         cout<< "Banana" <<endl;
19     }
20 };
21 
22 class Apple: public Fruit{
23 public:
24     void print(){
25         cout<< "Apple" <<endl;
26     }
27 };
28 
29 class Pear: public Fruit{
30 public:
31     void print(){
32         cout<< "Pear" <<endl;
33     }
34 };
35 
36 class Peach: public Fruit{
37 public:
38     void print(){
39         cout<< "Peach" <<endl;
40     }
41 };
42 
43 int main(void)
44 {
45     Banana ban;
46     Apple ape;
47     Pear par;
48     Peach pch;
49     Fruit *frt[] = {&ban, &ape, &par, &pch};
50 
51     for(int i = 0; i < 4; i++)
52         frt[i]->print();        // 一個基類指針,分別調用不同的子類對象(動態多態)
53 
54     system("PAUSE");
55     return 0;
56 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM