C++类的继承(.h文件.cpp文件分开实现版)

项目视图如下

类视图如下

类说明

CRectangle定义了一个矩形
CCuboid定义了一个立方体
立方体子类继承了矩形父类,所以矩形的宽和高要是保护类型的
在初始化的时候要显式调用CRectangle两个参数的构造函数

各文件完整代码

Rectangle.h

注意事项

在.h文件声明类,需要加上
#ifndef [类名]_H
#define [类名]_H
....
#endif
#ifndef CRectangle_H
#define CRectangle_H
class CRectangle{
public:
    double area();
    double circum();
    CRectangle(int width,int height);
    ~CRectangle();
protected:
    int height;
    int width;
};
#endif

Rectangle.cpp

#include "Rectangle.h"
#include "iostream"
using namespace std;
CRectangle::~CRectangle(){
    cout<<"销毁CRectangle对象"<<endl;
}
CRectangle::CRectangle(int width,int height){
    this->width=width;
    this->height=height;
    cout<<"建立CRectangle对象"<<endl;
}
double CRectangle::area()
{
    return width*height;
}
double CRectangle::circum()
{
    return 2*(width+height);
}

Cuboid.h

#ifndef CCuboid_H
#define CCuboid_H
#include "Rectangle.h"
class CCuboid:public CRectangle{
public:
    CCuboid(int width,int height,int length);
    ~CCuboid();
    double volume();
private:
    int length;
};
#endif

Cuboid.cpp

#include "Cuboid.h"
#include "Rectangle.h"
#include "iostream"
using namespace std;
CCuboid::~CCuboid(){
    cout<<"销毁CCuboid对象"<<endl;
}
CCuboid::CCuboid(int width,int height,int length):CRectangle(width,height)
{
    this->length=length;
    cout<<"建立CCuboid对象"<<endl;
}
double CCuboid::volume()
{
    return width*height*length;
}

Main.cpp

#include "iostream"
#include "Rectangle.h"
#include "Cuboid.h"
using namespace std;
int main()
{
    CRectangle r(5,5);
    cout<<"面积 "<<r.area()<<endl;
    cout<<"周长 "<<r.circum()<<endl;
    CCuboid c(5,5,5);
    cout<<"体积 "<<c.volume()<<endl;
    return 1;
}

运行结果如下

建立CRectangle对象
面积 25
周长 20
建立CRectangle对象
建立CCuboid对象
体积 125
销毁CCuboid对象
销毁CRectangle对象
销毁CRectangle对象
Press any key to continue
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容