c++聚合

简单来说就是在类里面定义其它类的对象(以指针形式定义),但是与组合有区别,组合里面定义的需要和总类对象共生死,聚合不会随着总类对象结束而消失。

头文件1:

Computer头文件

#pragma once

#include "Cpu.h"

class VoiceBox;		// 告诉编译器有这么一个类


class Computer {
public:
	Computer(const char *cpu_type, const char *cpu_parameter, const int hard_disk, const int memory);
	~Computer(void);

	/*********聚合********/
	void Box(VoiceBox *box);	

private:
	Cpu cpu;		// Computer 和 Cou 是 “组合” 关系
	//Cpu *cpu;
	int hard_disk;	// 硬盘
	int memory;		// 内存

	/*******聚合****/
	VoiceBox *box;
};

Computer文件

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


Computer::Computer(const char *cpu_type, const char *cpu_parameter, 
	const int hard_disk,const int memory):cpu(cpu_type, cpu_parameter) {
	this->hard_disk = hard_disk;
	this->memory = memory;

	//this->cpu = new Cpu(cpu_type, cpu_parameter);

	cout << __FUNCTION__ << endl;
}

Computer::~Computer(void) {
	//delete cpu;
}

/************* 聚合 ********************/
void Computer::Box(VoiceBox *box) {
	this->box = box;
}

头文件2:

Cpu头文件

#pragma

#include <string>

using namespace std;

class Cpu {
public:
	Cpu(const char *cpu_type, const char *cpu_parameter);
	~Cpu(void);

private:
	string cpu_type;		// 型号
	string cpu_parameter;	// 参数
};

Cpu文件

#include "Cpu.h"
#include <iostream>

Cpu::Cpu(const char *cpu_type, const char *cpu_parameter) {
	this->cpu_type = cpu_type;
	this->cpu_parameter = cpu_parameter;

	cout << __FUNCTION__ << endl;
}

Cpu::~Cpu(void) {

}

头文件3:

头文件VoiceBox

#pragma

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

VoiceBox文件

#include "VoiceBox.h"

VoiceBox::VoiceBox(void) {

}

VoiceBox::~VoiceBox(void) {

}

mina文件

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

using namespace std;

int main(void) {
	Computer c1("internex", "i7", 500, 8);
	VoiceBox box;
	
	c1.Box(&box);


	system("pause");
	return 0;
}

聚合不是组成关系,被包含的对象,也可能被其他对象包含。
拥有者,不需要对被拥有的对象的生命周期负责。

UML中的组合表示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cpp_learners

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值