简单来说就是在类里面定义其它类的对象(以指针形式定义),但是与组合有区别,组合里面定义的需要和总类对象共生死,聚合不会随着总类对象结束而消失。
头文件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中的组合表示: