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 未被消除,消除的是它指向的空間
}