实现一个图形类(Shape),包含受保护成员属性:周长、面积,
公共成员函数:特殊成员函数书写
定义一个圆形类(Circle),继承自图形类,包含私有属性:半径
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。
- #include
-
- using namespace std;
-
- //图形类
- class Shape
- {
- protected:
- double len;
- double Area;
-
- public:
- //无参构造
- Shape():len(0),Area(0)
- {
- cout<<"Shape:无参构造"<
- }
-
- //有参构造
- Shape(int l,int a):len(l),Area(a)
- {
- cout<<"Shape:有参构造"<
- }
-
- //析构函数
- ~Shape()
- {
- cout<<"析构函数"<
- }
-
- //拷贝构造函数
- Shape(const Shape &other):len(other.len),Area(other.Area)
- {
- cout<<"拷贝构造函数"<
- }
-
- //拷贝赋值函数
- Shape &operator=(const Shape &other)
- {
- this->len=other.len;
- this->Area=other.Area;
- return *this;
- }
- };
-
- //圆形类
- class Circle:public Shape
- {
- private:
- double R;
- public:
- //无参构造
- Circle()
- {
- cout<<"Circle:无参构造"<
- }
-
- //有参构造
- Circle(double r):R(r)
- {
- len=2*3.14*r;
- Area=r*r*3.14;
- cout<<"Circle:有参构造"<
- }
-
- //析构函数
- ~Circle()
- {
- cout<<"析构函数"<
- }
-
- //拷贝构造函数
- Circle(Circle &other):Shape(other.len,other.Area),R(other.R)
- {
- cout<<"拷贝构造函数"<
- }
-
- //拷贝赋值函数
- Circle &operator=(const Circle &other)
- {
- this->R=other.R;
- this->len=other.len;
- this->Area=other.Area;
- return *this;
- }
-
- //求周长
- double c_len()
- {
- return len;
- }
-
- //求面积
- double c_area()
- {
- return Area;
- }
-
- };
-
- //矩形类
- class Rect:public Shape
- {
- private:
- double cha;
- double gao;
- public:
- //无参构造
- Rect()
- {
- cout<<"Rect:无参构造"<
- }
-
- //有参构造
- Rect(double c,double g):cha(c),gao(g)
- {
- len=2*(c+g);
- Area=c*g;
- cout<<"Rect:有参构造"<
- }
-
- //析构函数
- ~Rect()
- {
- cout<<"析构函数"<
- }
-
- //拷贝构造函数
- Rect(const Rect &other):Shape(other.len,other.Area),cha(other.cha),gao(other.gao)
- {
- cout<<"拷贝构造函数"<
- }
-
- //拷贝赋值函数
- Rect &operator=(const Rect &other)
- {
- len=other.len;
- Area=other.Area;
- cha=other.cha;
- gao=other.gao;
- return *this;
- }
-
- //求周长
- double r_len()
- {
- return cha*2+gao*2;
- }
-
- //求面积
- double r_area()
- {
- return cha*gao;
- }
-
- };
-
- int main()
- {
- Circle y(5);
- cout<<"这个圆形的周长为"<
c_len()< - cout<<"这个圆形的面积为"<
c_area()< -
- Rect r(5,8);
- cout<<"这个矩形的周长为"<
r_len()< - cout<<"这个矩形的面积为"<
r_area()< - return 0;
- }


-
相关阅读:
Vue中图片上传组件封装-antd的a-upload二次封装-案例
VoLTE题库(含解析)-中高级必看
GPU驱动及CUDA安装流程介绍
Nacos环境隔离
当黑客遇到电脑白痴
#gStore-weekly | gStore源码解析(四):安全机制之黑白名单配置解析
Python 连接数据库添加字段
财务对账-财务收发存-业务收发存
MyBatis:基础入门
(封装)已知的一个类Student
-
原文地址:https://blog.csdn.net/2201_75732711/article/details/132839614
-
最新文章
-
沪漂五周年了:我越来越迷茫了
Agentic Skill Routing 实战:别再把所有 Skill 塞进 AI Agent 上下文
MySQL-Seconds_behind_master的精度误差
[MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱省时间
AI的至暗历史:从万众期待到被政府撤资,AI的两次死亡徘徊
Agent OS :五种驯服不确定性的范式
PortSwigger SQL注入LAB11
数据库即时编译JIT
[Begin]AI Learn Data Day 0
深度学习进阶(二十七)现代 LLM 的核心架构设计其二:SwiGLU