C++ 课程作业 继承与派生(Shape Circle Rectangle类的设计,继承与派生)

首先是题目
【问题描述】
编写一个Shape类并派生出Circle类和Rectangle类,观察运行机制。
shape类有以下成员
1)私有成员m_ID
2)公有getter和setter
3)计算面积函数getArea(),返回0;
4)构造与析构函数
Circle类从shape类继承,并派生以下成员
1)私有成员r
2)公有getter和setter
3)计算面积函数getArea(),返回计算面积;
4)构造与析构函数
Rectangle类从shape类继承,并派生以下成员
1)私有成员h,w
2)公有getter和setter
3)计算面积函数getArea(),返回计算面积;
4)构造与析构函数

然后是代码

#include 
using namespace std;
const  float  pi = 3.14159;
class Shape
{
    int m_ID;//私有成员m_ID
public:
    void getID(int id) { m_ID = id; }
    int setID() { return m_ID; }//getter和setter函数
    int getArea() { return 0; }//计算面积函数getArea(),返回0;
    Shape(int i=0) { m_ID = i; cout << "Shape constructor called:" << m_ID << endl; }//这里需要先设置默认值,不然下面派生类调用时,没有默认构造函数可用
    ~Shape() { cout << "Shape destructor called:" << m_ID << endl; }
};
class Circle :public Shape
{
    int r;//私有成员r
public:
    void getr(int i) { r = i; }
    int setr() { return r; }//getter和setter函数
    float getArea() { return pi * r * r; }//计算面积函数getArea()
    Circle(int newr, int newid) :r(newr), Shape(newid) { cout << "Circle constructor called:" << setID()<< endl; }//*派生类在初始化参数时需要将基类的参数也初始化*
    ~Circle() { cout << "Circle destructor called:" << setID() << endl; }//通过调用基类的公有成员调用基类的私有成员
};
class Rectangle :public Shape
{
    int h, w;//私有成员h,w
public:
    int getArea() { return h * w; }//计算面积函数getArea()
    int geth() { return h; }
    void seth(int h1) { h = h1; }
    int getw() { return w; }
    void setw(int w1) { w = w1; }getter和setter函数
    Rectangle(int newh, int neww, int newid):h(newh),w(neww),Shape(newid) { cout << "Rectangle constructor called:" << setID() << endl; }//定义的形参都是在私有成员前加new,组合而成
    ~Rectangle() { cout << "Rectangle destructor called:" << setID() << endl; }
};
int  main()
{
    Shape  s(1);//1表示ID
    Circle  c(4, 2);//4表示半径,2表示ID
    Rectangle  r(4, 5, 3);//4和5表示长和宽,3表示ID
    cout << "Shape的面积" << s.getArea() << endl;
    cout << "Circle的面积" << c.getArea() << endl;
    cout << "Rectangle的面积" << r.getArea() << endl;
}

总结:看了教学视频隔天写的,结果好多都忘了,又回去重看了一遍(唉)
需要记住的是在初始化派生类的参数时同时要初始化基类的参数。
通过调用基类的公有成员函数来调用基类的私有成员。

你可能感兴趣的:(C++ 课程作业 继承与派生(Shape Circle Rectangle类的设计,继承与派生))