在子类中调用父类的带参数的构造函数[图](2)
例2-14
#include <iostream.h>
class animal
{
public:
animal(int height, int weight)
{
cout<<"animal construct"<<endl;
}
…
};
class fish:public animal
{
public:
fish():animal(400,300)
{
cout<<"fish construct"<<endl;
}
…
};
void main()
{
fish fh;
}
注意程序中以粗体显示的代码。在fish类的构造函数后,加一个冒号(:),然后加上父类的带参数的构造函数。这样,在子类的构造函数被调用时,系统就会去调用父类的带参数的构造函数去构造对象。这种初始化方式,还常用来对类中的常量(const)成员进行初始化,如下面的代码所示:
class point
{
public:
point():x(0),y(0)
private:
const int x;
const int y;
};
当然,类中普通的成员变量也可以采取此种方式进行初始化,然而,这就没有必要了。
- 上一篇:VC++深入详解:类的继承[图]
- 下一篇:VC++深入详解:虚函数与多态性[组图]