C++面向对象的程序设计7——组合和聚合

组合和聚合是建模的常用手段,其中组合是整体和部分的关系,它们是同生共死的,例如电脑和cpu的关系,电脑坏了,cpu也不可以使用;而聚合则是两个类的聚合,当一个类消失时,另一个类并不会消失,例如电脑和音箱,音箱知识电脑的一个设备,并不会因为电脑坏了导致音箱不能使用。

样例代码如下:

Computer类:

#pragma once
#include <string>
#include <iostream>
#include "Cpu.h"


using namespace std;

class VoiceBox;

class Computer
{
public:
	Computer(string, string, int, int);
	void addBox(VoiceBox *);
	~Computer();
private:
	VoiceBox *box;
	// Cpu cpu;
	Cpu *cpu;
	int memory;
	int externalMemory;
};


#include "Computer.h"


Computer::Computer(string cpuType, string cpuVersion, int memory, int externalMemory)// :cpu(cpuType, cpuVersion)  // 组合部件使用初始化列表进行初始化
{
	this->cpu = new Cpu(cpuType, cpuVersion);  // 使用动态内存的方式创建
	this->memory = memory;
	this->externalMemory = externalMemory;
	cout << __FUNCTION__ << endl;
}


void Computer::addBox(VoiceBox *box)
{
	this->box = box;

}

Computer::~Computer(void)
{
	delete cpu;  // 释放cpu的资源
	cout << __FUNCTION__ << endl;
}

CPU类

#pragma once
#include <string>
#include <iostream>

using namespace std;

class Cpu
{
public:
	Cpu(string, string);
	~Cpu(void);
private:
	string cpuType;
	string version;
};

#include "Cpu.h"


Cpu::Cpu(string cpuType, string cpuVersion)
{
	this->cpuType = cpuType;
	this->version = cpuVersion;
	cout << __FUNCTION__ << endl;
}


Cpu::~Cpu(void)
{
	cout << __FUNCTION__ << endl;
}

VoiceBox类

#pragma once
#include <iostream>
#include <string>

using namespace std;

class VoiceBox
{
public:
	VoiceBox();
	~VoiceBox();
};

#include "VoiceBox.h"


VoiceBox::VoiceBox(void)
{
	cout << __FUNCTION__ << endl;
}


VoiceBox::~VoiceBox(void)
{
	cout << __FUNCTION__ << endl;
}

main函数

#include "Computer.h"
#include "VoiceBox.h"



void test(VoiceBox *box)
{
	// 组合是整体宇部分的关系,同生共死的
	Computer computer("Intel", "i7", 16, 512);
	// 聚合不是同生共死的关系,当电脑坏了之后音响还是可以继续使用
	computer.addBox(box);
}

int main()
{
	VoiceBox box;
	test(&box);
	system("pause");
	return 0;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值