代码清单 2.2.1
#include <iostream>#include <string.h>#include <unistd.h>using namespace std;class Human{public:void eating(void) { cout << "use hand to eat" << endl; }};class Englishman : public Human{public:void eating(void) { cout << "use knife to eat" << endl; }};class Chinese : public Human{public:void eating(void) { cout << "use chopsticks to eat" << endl; }};void test_eating(Human &h){h.eating();}int main(int argc, char **argv){Human h;Englishman e;Chinese c;test_eating(h);test_eating(e);test_eating(c);return 0;}
运行结果:
use hand to eat use hand to eat use hand to eat
代码清单 2.2.2
#include <iostream>#include <string.h>#include <unistd.h>using namespace std;class Human{public:virtual void eating(void) { cout << "use hand to eat" << endl; }};class Englishman : public Human{public:void eating(void) { cout << "use knife to eat" << endl; }};class Chinese : public Human{public:void eating(void) { cout << "use chopsticks to eat" << endl; }};void test_eating(Human &h){h.eating();}int main(int argc, char **argv){Human h;Englishman e;Chinese c;test_eating(h);test_eating(e);test_eating(c);return 0;}
运行结果
use hand to eat use knife to eat use chopsticks to eat
非虚函数,在编译时会直接确定调用关系
虚函数,则不然,在运行时决定调用关系
虚函数还有一个非常重要的作用: 通过指针进行调用,虚函数可以理解为一个对外引出的接口。而成员函数由于包含对象信息不具备这个特性。
函数指针不能直接调用类的成员函数,需采取间接的方法,原因是成员函数指针与一般函数指针有根本的不同,成员函数指针除包含地址信息外,同时携带其所属对象信息。
而虚函数巧妙的脱离了与对象的绑定,具备独立的地址。
例如:
A类中创建了B类的对象指针 *ptr ,而B类中包含一个虚函数virtual c(void);
那么A类就可以通过 ptr->c的方式进行调用
