举例:
在一个聊天室里,有一群人,每个人都会说自己的话
使用一个结构把一群人表达出来
#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] = ŋ 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] = ŋ 36 37 ary[0]->speak(); 38 ary[1]->speak(); 39 ary[2]->speak(); 40 return 0; 41 }
out:
C++的继承关系中,有两种成员函数:
1、基类希望其派生类进行覆盖的函数;
2、基类希望派生类直接继承而不需要改变的函数;
对于情况1,基类通常将其定义为虚函数Virtual。当我们使用指针或引用调用该虚函数时,该调用将被动态绑定。