【自用24.】C++组合和聚合

组合和聚合,不是C++的语法要求,是应用中的常用手段。

组合

代码如下:

Computer.h

#pragma once
#include "CPU.h"

class Computer
{
public:
	Computer(const char * cpubrand, const char * cpuversion, int hardDisk, int memory);
	~Computer();

private:
	CPU cpu;//Computer和CPU之间就是组合关系
	int hardDisk;//硬盘,单位G
	int memory;//内存,单位G
};

Computer.cpp

#include "Computer.h"

Computer::Computer(const char* cpubrand, const char* cpuversion, int hardDisk, int memory) : cpu(cpubrand, cpuversion) {
	this->hardDisk = hardDisk;
	this->memory = memory;

	std::cout << __FUNCTION__ << std::endl;
}

Computer::~Computer() {
	std::cout << __FUNCTION__ << std::endl;
}

CPU.h

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

using namespace std;

class CPU
{
public:
	CPU(const char* brand = "intel", const char* version = "i5");
	~CPU();

private:
	string brand;//品牌
	string version;//型号
};


CPU.cpp

#include "CPU.h"

CPU::CPU(const char* brand, const char* version) {
	this->brand = brand;
	this->version = version;

	std::cout << __FUNCTION__ << std::endl;
}

CPU::~CPU() {
	std::cout << __FUNCTION__ << std::endl;
}

main.cpp

#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
#include "Computer.h"

using namespace std;

void test() {
	Computer a("intel", "i9", 1000, 8);
}

int main(void) {
	test();

	system("pause");
	return 0;
}

小结:

被拥有的对象(芯片)的生命周期与其拥有者(计算机)的生命周期是一致的。

计算机被创建时,芯片也随之创建。

计算机被销毁时,芯片也随之销毁。

拥有者需要对被拥有者负责,是一种比较强的关系,是整体与部分的关系。

具体组合方式:

1)被组合的对象直接使用成员对象。(常用)

2)使用指针表示被组合的对象,在构造函数中,创建被组合的对象;在析构函数中,释放被组合的对象。

UML中的组合表示:

注意包含者使用实心菱形

【补充】UML画图工具:starUML

聚合

使用结果

 

代码

Computer.h

#pragma once
#include "CPU.h"
#include "VoiceBox.h"

class VoiceBox;

class Computer
{
public:
	Computer(const char * cpubrand, const char * cpuversion, int hardDisk, int memory);
	~Computer();
	void addVoiceBox(VoiceBox* box);

private:
	CPU cpu;//Computer和CPU之间就是组合关系
	int hardDisk;//硬盘,单位G
	int memory;//内存,单位G
	VoiceBox* box;
};

main.cpp

#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
#include "Computer.h"

using namespace std;

void test() {
	Computer a("intel", "i9", 1000, 8);
}

void test(VoiceBox* box) {
	Computer myComputer("intel", "i9", 1000, 8);
	myComputer.addVoiceBox(box);
}

int main(void) {
	//test();
	VoiceBox box;
	test(&box);

	system("pause");
	return 0;
}

另外需要先创建VoiceBox类,这部分比较简单,就没有在这里放代码

聚合不是组成关系,被包含的对象,也可能被其他对象包含。

拥有者,不需要对被拥有的对象的生命周期负责。

UML中的组合表示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值