[置顶] c++类的继承(inheritance)
在C++中,所谓“继承”就是在一个已存在的类的基础上建立一个新的类。已存在的类(例如“马”)称为“基类(base class )”或“父类(father class )”。新建的类(例如“公马”)称为“派生类(derived class )”或“子类(son class )”。
以上介绍的是最简单的情况:一个派生类只从一个基类派生,这称为单继承(single inheritance),这种继承关系所形成的层次是一个树形结构。一个派生类不仅可以从一个基类派生,也可以从多个基类派生。一个派生类有两个或多个基类的称为多重继承(multiple inheritance)。关于基类和派生类的关系,可以表述为:派生类是基类的具体化,而基类则是派生类的抽象。
声明派生类的一般形式为
class 派生类名:[继承方式] 基类名{派生类新增加的成员};
继承方式包括: public (公用的),private (私有的)和protected(受保护的),此项是可选的,如果不写此项,则默认为private(私有的)。
Eg:
class a :b
{
};
一个类的继承方式如果被制定为私有,那么在子类中它在子类中的所有成员都将是私有的。如果被指定为protected,则父类中public的成员在子类中变为protected(protected 和 private都不变化),如果被指定为public 那么所有都不变。
#include <iostream> #define PI 3.1415926 using namespace std; class Pointer { public: Pointer(){} Pointer(double a,double b):x(a),y(b){} protected: double x; double y; friend ostream &operator<<(ostream& out,Pointer &P); }; ostream &operator<<(ostream& out,Pointer &P) { cout<<" Pointer: x,y is "<<P.x<<","<<P.y<<endl; return out; } class Circle:public Pointer { public: Circle(){} Circle(double a,double b,double dr):Pointer(a,b),r(dr){} protected: double r; public: double get_area() { return PI*r*r; } friend ostream &operator<<(ostream& out,Circle &c); }; ostream &operator<<(ostream& out,Circle &c) { cout<<"Circle: radius :"<<c.r; out<<c.x<<endl; out<<c.y<<endl; return out; } class Cylinder:Circle { public: Cylinder(){} Cylinder(double a,double b,double c,double d):Circle(a,b,c),h(d) { } protected: double h; public: double get_Volume() { return Circle::get_area()*h; } double get_area() { return 2*Circle::get_area()+2*PI*r*h; } friend ostream &operator<<(ostream& out,Cylinder &c); }; ostream &operator<<(ostream& out,Cylinder &c) { cout<<"cylinder dimensions"<<endl; cout<<"x: "<<c.x<<endl; cout<<"y: "<<c.y<<endl; cout<<"radius "<<c.r<<endl; cout<<"height "<<c.h<<endl; return out; } int main() { Pointer p(2,3); Circle c(7,5,6); Cylinder cy(10,12,11,13); cout<<p; cout<<c; cout<<"area of circle :"<<c.get_area()<<endl; cout<<cy; cout<<"area of cylinder base is "<<cy.get_area()<<endl; return 0; }