必备技能10.5:多层继承
到目前为止,我们使用到的继承关系只是一个基类和一个派生类。然而,我们是可以创建任意多层的继承关系的。正如在前面所提到的那样,把一个派生类作为另外一个类的基类是完全可以接受的。例如,有三个类A,B和C。C可是是从B继承而来的,同时B可以是从A继承而来的。当发生这样的情况的时候,每个派生类都继承了它所有基类的所有属性。针对刚才的例子,C就继承了A和B的全部属性。
为了理解多层继承的作用,我们来研究下面的程序。其中,Triangle类被作为基类来创建派生类ColoreTriangle。ColorTriangle就拥有了Triangle类和TwoDShape类的全部属性。
//多层继承
#include <iostream>
#include <cstring>
using namespace std;
//二维对象类
class TwoDShape
{
double width;
double height;
public:
//缺省的构造函数
TwoDShape()
{
width = height = 0;
}
//构造函数
TwoDShape(double w,double h)
{
width = w;
height = h;
}
//构造高度和宽度相等的对象
TwoDShape(double x)
{
width = height = x;
}
void showDim()
{
cout << "Width and height are "
<< width << " and " << height << "\n";
}
//访问函数
double getWidth() { return width; };
double getHeight() { return height; };
void setWidth(double w ) { width = w ; };
void setHeight(double h ) { height = h; };
};
//Triangle类是从TwoDShape类中继承而来的
class Triangle : public TwoDShape
{
char style[20];
public:
//缺省的构造函数。这将自动调用TwoDShape的缺省构造函数
Triangle()
{
strcpy(style,"unknown");
}
//有三个参数的构造函数
Triangle( char *str, double w, double h):TwoDShape(w,h)
{
strcpy(style,str);
}
//构建一个等腰三角形
Triangle(double x):TwoDShape(x)
{
strcpy(style,"isoscoles");
}
double area()
{
return getWidth() * getHeight() / 2;
}
void showStyle()
{
cout << "Triangle is " << style << "\n";
}
};
//对Triangle进行扩展
class ColorTriangle : public Triangle
{
char color[20];
public:
ColorTriangle(char * clr, char *style, double w, double h):Triangle(style, w, h)
{
strcpy(color,clr);
}
//显示颜色
void showColor()
{
cout << "Color is " << color << "\n";
}
};
int main()
{
ColorTriangle t1("Blue", "Right", 8.0, 12.0);
ColorTriangle t2("Red", "isosceles", 2.0, 2.0);
cout<<"Info for t1: \n";
t1.showStyle();
t1.showDim();
t1.showColor();
cout << "Area is " << t1.area() << "\n";
cout << "\n";
cout<<"Info for t2: \n";
t2.showStyle();
t2.showDim();
t2.showColor();
cout << "Area is " << t2.area() << "\n";
return 0 ;
}
上面程序的输出如下:
Info for t1:
Triangle is Right
Width and height are 8 and 12
Color is Blue
Area is 48
Info for t2:
Triangle is isosceles
Width and height are 2 and 2
Color is Red
Area is 2
作为继承关系中的派生类,ColorTriangle类拥有了其基类Triangle和TwoDShape类的属性,并增加了自己需要的信息,也是特有的信息。这也是继承的一大好处,使得代码可以重用。
这个例子中我们看看到另外一点。那就是在继承关系中,如果基类的构造函数需要参数,那么所有派生类的构造函数就必须为其传入这些参数,而不管派生类是否需要自己的参数。