1.类继承
基于已经定义好的类来获得新的类,使得新类具有已定义类的成员属性,从而简化了新类的定义,已定义类称为基类(父类),
新类称为派生类(子类)。派生类可继承多个基类的数据成员和成员函数。
2. 派生类构造函数的形式
派生类构造函数名(参数列表):基类构造函数名(参数列表)
{
派生类构造函数数据成员初始化;
};
即对派生类对象进行初始化时,仍需对基类进行初始化。
3. 派生类构造函数执行顺序
a. 派生类构造函数首先调用基类构造函数;
b. 然后调用派生类构造函数;
c. 然后调用派生类析构函数;
d. 最后调用基类析构函数;
4. 类继承的三种类型
a. 公有继承,基类的公有成员和保护成员变成派生类的公有成员和保护成员
b. 保护继承,基类的公有成员和保护成员变成派生类的保护成员
c. 私有继承,基类的公有成员和保护成员变成派生类的私有成员
5. 多继承的形式
class 派生类名:public 基类1名,public 基类2名
{
派生类定义
};
6. 代码实例
#include <iostream>
using namespace std;
//定义基类
class Box
{
protected:
int width;
int height;
public:
Box(int w, int h);
int cal_area();
~Box();
};
Box::Box(int w,int h)
{
cout << "初始化基类构造函数" << endl;
width = w;
height = h;
}
int Box::cal_area()
{
return width*height;
}
Box::~Box()
{
cout << "删除基类对象" << endl;
}
//定义派生类
class Shape:public Box
{
private:
int depth;
public:
//构造函数
//Shape(int w, int h, int d) :Box(w, h) { depth = d; };
Shape(int w, int h, int d);
int cal_volume();
~Shape()
{
cout << "删除派生类对象" << endl;
}
};
Shape::Shape(int w, int h, int d):Box(w,h)
{
cout << "初始化派生类构造函数" << endl;
depth = d;
}
int Shape::cal_volume()
{
int area = cal_area();
return area*depth;
}
void main()
{
Box box1(1, 2);
cout << "调用基类对象成员函数:" << box1.cal_area() << endl;
Shape shape(1, 2, 3);
cout << "调用派生类对象成员那函数:" << shape.cal_volume() << endl;
}