1. 程式人生 > 實用技巧 >C++入門 -- 多型與虛擬函式

C++入門 -- 多型與虛擬函式

舉例:

在一個聊天室裡,有一群人,每個人都會說自己的話

使用一個結構把一群人表達出來

#include <stdlib.h>

#include <iostream>
#include <string>
using namespace std;

class CPerson {
   public:
    CPerson() { m_nType = 0; }
    void speak() { cout << "speak" << endl; }
    int m_nType;
};

class CChinese : public
CPerson { public: CChinese() { m_nType = 1; } void speak() { cout << "speak Chinese" << endl; } }; class CEnglish : public CPerson { public: CEnglish() { m_nType = 2; } void speak() { cout << "speak English" << endl; } }; int main(int argc, char const* argv[]) { CChinese chs; CChinese chs1; CEnglish eng;
// some person CPerson* ary[3]; ary[0] = &chs; //子類轉換為父類 ary[1] = &chs1; ary[2] = &eng; ary[0]->speak(); //使用父類的指標呼叫,用的仍是父類的記憶體 ary[1]->speak(); ary[2]->speak(); for (int i = 0; i < 3; i++) { cout << i + 1; if (ary[i]->m_nType == 1
) { CChinese* pChs = (CChinese*)ary[i]; pChs->speak(); } else if (ary[i]->m_nType == 2) { CEnglish* pEng = (CEnglish*)ary[i]; pEng->speak(); } } return 0; }

使用以上方法,每當增加一個人時,就會很麻煩

C++引用虛擬函式實現通過基類訪問派生類的函式

 1 #include <stdlib.h>
 2 
 3 #include <iostream>
 4 #include <string>
 5 using namespace std;
 6 
 7 class CPerson {
 8    public:
 9     CPerson() { m_nType = 0; }
10     virtual void speak() { cout << "speak" << endl; }   //虛擬函式
11     int m_nType;
12 };
13 
14 class CChinese : public CPerson {
15    public:
16     CChinese() { m_nType = 1; }
17     void speak() { cout << "speak Chinese" << endl; }
18 };
19 
20 class CEnglish : public CPerson {
21    public:
22     CEnglish() { m_nType = 2; }
23     void speak() { cout << "speak English" << endl; }
24 };
25 int main(int argc, char const* argv[]) {
26     CChinese chs;
27     CChinese chs1;
28     CEnglish eng;
29 
30     // some person
31     CPerson* ary[3];
32 
33     ary[0] = &chs;
34     ary[1] = &chs1;
35     ary[2] = &eng;
36 
37     ary[0]->speak();
38     ary[1]->speak();
39     ary[2]->speak();
40     return 0;
41 }
virtual

out: