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

运行结果:

use hand to eat use hand to eat use hand to eat

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

运行结果

use hand to eat use knife to eat use chopsticks to eat

非虚函数,在编译时会直接确定调用关系
虚函数,则不然,在运行时决定调用关系

虚函数还有一个非常重要的作用: 通过指针进行调用,虚函数可以理解为一个对外引出的接口。而成员函数由于包含对象信息不具备这个特性。
函数指针不能直接调用类的成员函数,需采取间接的方法,原因是成员函数指针与一般函数指针有根本的不同,成员函数指针除包含地址信息外,同时携带其所属对象信息。
而虚函数巧妙的脱离了与对象的绑定,具备独立的地址。
例如:
A类中创建了B类的对象指针 *ptr ,而B类中包含一个虚函数virtual c(void);
那么A类就可以通过 ptr->c的方式进行调用