1.派生类的定义
格式:
class 派生类名:[继承方式]基类名
{
派生类新增的成员;
}
继承方式:private public protected
注意:派生类继承基类的成员函数,但不继承构造函数
2.派生类构造函数的定义
派生类构造函数名(总参数列表):基类构造函数名(参数列表)
{派生类中新增成员变量初始化语句}
注意:若没有基类构造函数,则按默认构造函数初始化基类的变量
例子:
#include <iostream>
using namespace std;
class CRectangle
{
public:
CRectangle(int width,int height);
~CRectangle();
double circum();
double area();
protected:
int width;
int height;
};
CRectangle::CRectangle(int width,int height)
{
this->width=width;
this->height=height;
cout<<"create object"<<endl;
}
CRectangle::~CRectangle()
{
cout<<"delete object"<<endl;
}
double CRectangle::circum()
{
return 2*(width+height);
}
double CRectangle::area()
{
return width*height;
}
class CCuboid:public CRectangle
{
public:
CCuboid(int width,int height,int length);
//包括基类的成员变量,新增变量length
~CCuboid();
double volume();
private:
int length;
};
CCuboid::CCuboid(int widht,int height,int length):CRectangle(int width,int height)
{
//派生类构造函数,调用基类构造函数
this->length=length;
cout<<"create new object"<<endl;
}
CCuboid::~CCuboid()
{
cout<<"delete the new object"<<endl;
}
double CCuboid::volume()
{
return width*height*length;
}
void main ()
{
CCuboid *pCuboid=new CCuboid(30,20,100);//动态开辟空间
cout<<"the Cuboid's volume is :"<<pCuboid->volume()<<endl;
delete pCuboid;
pCuboid=NULL;//pCuboid 未被消除,消除的是它指向的空间
}