组合和聚合是建模的常用手段,其中组合是整体和部分的关系,它们是同生共死的,例如电脑和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;
}
运行结果: