C++类的建模手段:聚合

#include "Computer.h"
#include "Music_Box.h"
#include <Windows.h>
//类与对象建模手段: 聚合
//需求:给前面的计算机类配一个音响
void test(Music_Box*box){
	Computer T1(500,16);
	T1.MusicBox(box);
}
int main(){
	Music_Box box;
	test(&box);
	system("pause");
	return 0;
}
先创建一个计算机的类:
class Music_Box;//聚合可以不用包含要使用类的头文件的;
class Computer{
public:
	Computer(int hardDisk,int memory);
	~Computer(void);
	void MusicBox(Music_Box*box);//定义一个音响的接口;
	private:
		int hardDisk;//硬盘;
		int memory;//内存;
		Music_Box*box;//使用指针,Computer和Music_Box就是"聚合"
};
Computer::Computer(int hardDisk,int memory){
	this->hardDisk=hardDisk;
	this->memory=memory;
	std::cout<<"Computer"<<std::endl;
}


Computer::~Computer(void){
	std::cout<<"~Computer"<<std::endl;//测试查看调用的顺序
}
void Computer::MusicBox(Music_Box*box){
	this->box=box;
}
创建一个音响的类:
class Music_Box
{
public:
	Music_Box(void);
	~Music_Box(void);
};
Music_Box::Music_Box(void){
}
Music_Box::~Music_Box(void){
	std::cout<<"~Music_Box"<<std::endl;;//测试查看调用的顺序
}

在这里插入图片描述
运行结果:
先调用Computer构造函数
再调用Computer析构函数
音响的类Music_Box 并没有受到影响;
UML中的表示:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值