实现一个图形类(Shape),包含受保护成员属性:周长、面积,
公共成员函数:特殊成员函数书写
定义一个圆形类(Circle),继承自图形类,包含私有属性:半径
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。
- #include
-
- #define PI 3.14
-
-
-
- using namespace std;
-
-
- class Shape
- {
- protected:
- double cir;//周长
- double area;//面积
- public:
- Shape()//显性定义无参构造
- {
- cir = 0;
- area = 0;
- cout<<"无参构造函数"<
- }
- Shape(double cir, double area):cir(cir),area(area)
- {
- cout<<"有参构造函数"<
- }
- ~Shape()
- {
- cout<<"Shape::析构函数"<
- }
- Shape(const Shape &other):cir(other.cir),area(other.area)
- {
- cout<<"拷贝构造函数"<
- }
- Shape & operator=(const Shape &other)
- {
- this->cir = other.cir;
- this->area = other.area;
- cout<<"拷贝赋值函数"<
- return *this;
- }
- };
-
- class Circle:public Shape
- {
- private:
- double rad;
- public:
- Circle()//显性定义无参构造
- {
- rad = 0;
- cout<<"无参构造函数"<
- }
- Circle(double rad):rad(rad)
- {
- cout<<"有参构造函数"<
- }
- ~Circle()
- {
- cout<<"Circle::析构函数"<
- }
- Circle(const Circle &other):rad(other.rad)
- {
- cout<<"拷贝构造函数"<
- }
- Circle & operator=(const Circle &other)
- {
- if(this != &other)
- {
- this->rad = other.rad;
- }
- cout<<"拷贝赋值函数"<
- return *this;
- }
- double get_cir()//获取周长函数
- {
- this->cir = 2*PI*rad;
- return this->cir;
- }
- double get_area()
- {
- this->area = PI*rad*rad;
- return this->area;
- }
- };
-
- class Rect:public Shape
- {
- private:
- double len;
- double width;
- public:
- Rect()//显性定义无参构造
- {
- len = 0;
- width = 0;
- cout<<"无参构造函数"<
- }
- Rect(double len, double width):len(len),width(width)
- {
- cout<<"有参构造函数"<
- }
- ~Rect()
- {
- cout<<"Rect::析构函数"<
- }
- Rect(const Rect &other):len(other.len),width(other.width)
- {
- cout<<"拷贝构造函数"<
- }
- Rect & operator=(const Rect &other)
- {
- if(this != &other)
- {
- this->len = other.len;
- this->width = other.width;
- }
- cout<<"拷贝赋值函数"<
- return *this;
- }
- double get_cir()//获取周长函数
- {
- this->cir = 2*(len+width);
- return this->cir;
- }
- double get_area()
- {
- this->area = len*width;
- return this->area;
- }
- };
-
- int main()
- {
- Circle c1(1.1);
- cout<<"c1周长="<
get_cir()< - cout<<"c1面积="<
get_area()< -
- Circle c2;
- c2 = c1;
- cout<<"c2周长="<
get_cir()< - cout<<"c2面积="<
get_area()< -
- Rect r1(2,3);
- cout<<"r1周长="<
get_cir()< - cout<<"r1面积="<
get_area()< -
- Rect r2 = r1;
- cout<<"r2周长="<
get_cir()< - cout<<"r2面积="<
get_area()< - return 0;
- }


-
相关阅读:
Mybatis---从入门到深化
Kubernetes部署kubernates Nginx Ingress Controller
Bee1.17同时支持JDBC,安卓和鸿蒙;SQL Server分页,JPA支持(同步Maven)
【机器学习】近邻类模型:KNN算法在数据科学中的实践与探索
宠物用品做谷歌推广的三种形式
【uniapp】小程序自定义一个通用的返回按钮组件
罗翔:钱没了可以再挣,工作没了可以再找,朋友没了可以再交,爱情没了可以再去找。你生来就一无所有,何惧从头再来。...
【EasyExcel】Java将不同的.csv文件数据存入同一个.xlsx文件的不同sheet当中
知识付费免费开源项目-课程讲师教务真题
JVM参数配置 JDK1.8
-
原文地址:https://blog.csdn.net/qq_53478460/article/details/132839875