VC++深入详解:类的继承[图](2)
重写animal和fish类,让fish从animal继承,代码如例2-11所示(EX05.CPP)。
例2-11
#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
{
};
void main()
{
animal an;
fish fh;
an.eat();
fh.eat();
}
虽然fish类没有显式地编写一个方法,但fish从animal已经继承eat、sleep、breathe方法,我们通过编译运行可以看到结果。
下面,我们在animal类和fish类中分别添加构造函数和析构函数,然后在main函数中定义一个fish类的对象fh,看看在构造fish类的对象时,animal类的构造函数是否被调用;如果调用,animal类和fish类的构造函数的调用顺序是怎样的。完整代码如例2-12所示(EX06.CPP)。
例2-12
#include <iostream.h>
class animal
{
public:
animal()
{
cout<<"animal construct"<<endl;
}
~animal()
{
cout<<"animal destruct"<<endl;