在C++中,派生类的一般定义语法为:
class 派生类名:继承方式 基类名1,继承方式 基类名2,....,继承方式 基类名n
{
派生类成员声明;
};
派生类成员是指出了从基类继承来的所有成员之外,新增加的数据和函数成员。
#include <iostream>
using namespace std;
// 基类
class Shape {
protected:
int width = 0;
int height = 0;
public:
void setWidth(int width){
this -> width = width;
}
void setHeight(int height){
this -> height = height;
}
int getWidth(){
return this -> width;
}
int getHeight(){
return this -> height;
}
};
// 派生类
class Rectangle: public Shape{
public:
int getPerimeter(){
return (width + height) * 2;
}
int getArea(){
return (width * height);
}
};
int main(void){
Rectangle *rectangle = new Rectangle();
rectangle -> setWidth(4);
rectangle -> setHeight(3);
cout << "长:" << rectangle -> getHeight() << endl;
cout << "宽:" << rectangle -> getWidth() << endl;
cout << "周长:" << rectangle -> getPerimeter() << endl;
cout << "面积: " << rectangle -> getArea() << endl;
delete rectangle;
return 0;
}
注:
- 一个派生类,可以同时有多个基类,这种情况称为多继承,这时的骗谁呢该类同时得到了多个已有类的特征。
- 一个派生类只有一个直接基类的情况,称为单继承。
- 在派生过程中,派生出来的新类也同样可以作为基类再继续派生新的类,此外,一个基类可以同时派生出多个派生类。
- 一个类从父类继承来的特征也可以被其他新的类所继承,一个父类的特征,可以同时被多个子类继承,形成一个相互关联的类的家族,有时成为类族。
- 在类族中,直接参与派生出某类的基类成为直接基类,基类的基类甚至更高层的基类成为间接基类。
- 在派生类的定义中,除了要指定基类外,还需要指定继承方式。继承方式规定了如何访问从基类继承的成员。
- 在派生类的定义语句中,每一个“继承方式”,只限定紧随其后的基类。
- 继承方式关键字为:
public
,protected
和private
,分别表示公有继承、保护继承和私有继承。 - 如果不显示地给出继承方式关键字,系统的默认值就认为是私有继承(
private
)。 - 类的继承方式指定了派生类成员以及类外对象对于从基类继承来的成员的访问权限。