2.1面向对象程序设计基础(3)

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值