017_linuxC++之_多态的引入

多态:一种接口,多种方法(同一种调用方法,根据不同的对象,调用不同类中的函数)
静态联编:非虚函数,在编译时确定好
动态联编:   1. 对象里有指针,指向虚函数表
      2. 通过指针,找到表,调用虚函数
      3. 图二
      4. virtual来定义为虚函数

(一)首先我们来看静态联编,非多态的程序

 1 #include <iostream>
 2 #include <string.h>
 3 #include <unistd.h>
 4 
 5 using namespace std;
 6 
 7 class Human {
 8 public:
 9     void eating(void) { cout<<"use hand to eat"<<endl; }
10 };
11 
12 class Englishman : public Human {
13 public:
14     void eating(void) { cout<<"use knife to eat"<<endl; }
15 };
16 
17 
18 class Chinese : public Human {
19 public:
20     void eating(void) { cout<<"use chopsticks to eat"<<endl; }
21 };
22 
23 void test_eating(Human& h)
24 {
25     h.eating();
26 }
27 
28 int main(int argc, char **argv)
29 {
30     Human h;
31     Englishman e;
32     Chinese c;
33 
34     test_eating(h);
35     test_eating(e);
36     test_eating(c);
37 
38     return 0;
39 }
View Code

运行结果,调用的全部是Human中的,并不是我们想要的,因为这里是静态编译进去了,也就是说程序在编译时候就已经确定好就调用Human中的

(二)动态编译,实现多态,在类中定义时候增加virtual来实现这个函数为虚函数

 1 #include <iostream>
 2 #include <string.h>
 3 #include <unistd.h>
 4 
 5 using namespace std;
 6 
 7 class Human {
 8 public:
 9     virtual void eating(void) { cout<<"use hand to eat"<<endl; }
10 };
11 
12 class Englishman : public Human {
13 public:
14     virtual void eating(void) { cout<<"use knife to eat"<<endl; }
15 };
16 
17 
18 class Chinese : public Human {
19 public:
20     virtual void eating(void) { cout<<"use chopsticks to eat"<<endl; }
21 };
22 
23 void test_eating(Human& h)
24 {
25     h.eating();
26 }
27 
28 int main(int argc, char **argv)
29 {
30     Human h;
31     Englishman e;
32     Chinese c;
33 
34     test_eating(h);
35     test_eating(e);
36     test_eating(c);
37 
38     return 0;
39 }
View Code

运行结果,就实现了同一接口,不同调用的方法了

(三)更多具体的,,,,,,,

原文地址:https://www.cnblogs.com/luxiaoguogege/p/9696061.html