2.2.7 虚函数与多态性、纯虚函数(1)
1.虚函数与多态性
因为鱼的呼吸是吐泡泡,和一般动物的呼吸不太一样,所以我们在fish类中重新定义breathe方法。我们希望如果对象是鱼,就调用fish类的breathe()方法,如果对象是动物,那么就调用animal类的breathe()方法。程序代码如例2-16所示(EX08.CPP)。
例2-16
- #include <iostream.h>
- class animal
- {
- public:
- void eat()
- {
- cout<<"animal eat"<<endl;
- }
- void sleep()
- {
- cout<<"animal sleep"<<endl;
- }
- void breathe()
- {
- cout<<"animal breathe"<<endl;
- }
- };
- class fish:public animal
- {
- public:
- void breathe()
- {
- cout<<"fish bubble"<<endl;
- }
- };
-
- void fn(animal *pAn)
- {
- pAn->breathe();
- }
- void main()
- {
- animal *pAn;
- fish fh;
- pAn=&fh;
- fn(pAn);
- }
我们在fish类中重新定义了breathe()方法,采用吐泡泡的方式进行呼吸。接着定义了一个全局函数fn(),指向animal类的指针作为fn()函数的参数。在main()函数中,定义了一个fish类的对象,将它的地址赋给了指向animal类的指针变量pAn,然后调用fn()函数。看到这里,我们可能会有些疑惑,照理说,C++(www.cppentry.com)是强类型的语言,对类型的检查应该是非常严格的,但是,我们将fish类的对象fh的地址直接赋给指向animal类的指针变量,C++(www.cppentry.com)编译器居然不报错。这是因为fish对象也是一个animal对象,将fish类型转换为animal类型不用强制类型转换,C++(www.cppentry.com)编译器会自动进行这种转换。反过来,则不能把animal对象看成是fish对象,如果一个animal对象确实是fish对象,那么在程序中需要进行强制类型转换,这样编译才不会报错。
读者可以猜想一下例2-16运行的结果,输出的结果应该是"animal breathe",还是"fish bubble"呢?
运行这个程序,你将看到如图2.12所示的结果。
|
| 图2.12 EX09程序的运行结果(一) |