继承:
创建类时,不需要重写新的数据成员和成员函数。 您只需指定新类继承了现有类的成员。
将该现有的类称为基类,将新创建的类称为派生类。
例如:
//基类class Animal { //eat (函数//sleep ) }; //派生类class dog :公共动画(//bark ) )函数;派生类的定义:
类派生列表按以下格式命名一个或多个基类:
class derived-class : access-specifier base-class//access-specifier是在public、protected或private中定义的基本类型
例如:
# includeiostreamusingnamespacestd; //基类class shape { public : void set width (intw ) { width=w; }voidsetheight(inth ) { height=h; }受保护的:输入宽度; int height; (; //派生类class rectangle 3360公共形状(public : int getarea ) ) return ) width*height ); }; 输入主(void ) { Rectangle Rect; rect.setwidth(5; rect.Setheight(7; //输出对象面积cout ' total area : ' rect.getarea () endl; 返回0; } 访问控制和继承
派生类可以访问基类的所有非专用成员。 因此,如果基类的成员不希望访问派生类的成员函数,则必须在基类中将其声明为private。
根据您的访问权限,您可以总结各种访问类型,例如:
-访问--- -公共----protected---- private-- -同一类是是是否派生类是是否外部的类是否两个派生类继承所有基类方法。 但是,以下情况除外:
基类构造函数、析构函数和复制构造函数。 基类重载运算符。 基类的友元函数。继承类型
如果类是从基类派生的,则基类可以继承为几种类型: public、protected或private
使用不同类型的继承时,请遵循以下规则:
公共继承(public ) :如果一个类是从公共基类派生的,则基类的公共成员也是派生类的公共成员,基类的保护成员也是派生类的保护成员。 基类的专用成员不能直接从派生类中访问,但可以通过调用基类的公共成员和保护成员进行访问。
保护继承(protected ) :如果类是从保护基类派生的,则基类的公共成员和保护成员将成为派生类的保护成员。
专用继承(private ) :如果一个类出于私心派生为具有基类,则基类的公共成员和保护成员将成为派生类的专用成员。
多继承
c类可以从多个类中继承成员。 语法如下。
class派生类名称:继承方式1基类名称1、继承方式2基类名称2、…//各基类之间用逗号分隔{派生类体}; 例:
# includeiostreamusingnamespacestd; //基类shapeclassshape { public : void set width (intw ) { width=w; }voidsetheight(inth ) { height=h; }受保护的:输入宽度; int height; (; //基类paintcostclasspaintcost { public : intgetcost (intarea ) { return area * 70; }; //派生类class Rectangle: public Shape,publicpaintcost { public : int getarea () return ) width*height; }; 输入主(void ) { Rectangle Rect; int area; rect.setwidth(5; rect.Setheight(7; area=Rect.getArea (; //输出对象面积cout ' total area : ' rect.getarea () endl; //输出始终包含cout ' totalpaintcost : $ ' rect.get cost (area ) endl; 返回0; }