2

建模的常用手段:组合和聚合 - 理想主义者光芒万丈

 2 years ago
source link: https://www.cnblogs.com/ylww/p/16703536.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

  博客园  ::

首页  ::

新随笔  ::

联系 ::

订阅

 ::

管理

  46 随笔 :: 0 文章 :: 0 评论 ::

794 阅读

说明:组合和聚合,不是c++的语法要求,而是应用中的常用手段。

组合

构建一个计算机类,一台计算机,由CPU芯片,硬盘,内存等组成。

CPU芯片也使用类来表示。

2835841-20220917195749180-509494140.png
2835841-20220917195833436-454644417.png
2835841-20220917200010669-1389733254.png
2835841-20220917200046645-745937430.png
2835841-20220917200126761-982155711.png

运行结果:

2835841-20220917200219374-1644919160.png

这是会调用析构函数的。

2835841-20220917201736000-185175634.png

关于第二种组合模式: “组合Computer.h”文件中类中数据改写成 Cpu *cpu;,并将头文件改写成声明——>“组合Computer.cpp”文件中,在构造函数中

删去初始化列表部分,且在此函数中加入 this->cpu = new Cpu(cpuBrand, cpuVersion);——>“组合Computer.cpp”文件中,在

析构函数中delete cpu;。

 

2835841-20220917220811116-1582511343.png

聚合

给计算机配一台音响。

2835841-20220917215304544-1575155228.png
2835841-20220917215357248-246827056.png
2835841-20220917215858363-2081455679.png
2835841-20220917220037975-1474262196.png
2835841-20220917215346932-1191223780.png

 运行结果:

2835841-20220917220143218-619941045.png

2835841-20220917220423485-481118213.png

2835841-20220917220511823-897105625.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK