组合与聚合
组合
说明:组合和聚合,不是C++的语法要求,是应用中的常用手段。
组合
需求:
构建一个计算机类,一台计算机,由CPU芯片,硬盘,内存等组成。
CPU芯片也使用类来表示。
- Cpu类
#include <string>
class CPU
{
public:
CPU(const char *brand = "intel", const char *version="i5");
~CPU();
private:
std::string brand; //品牌
std::string version; //型号
};
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;
}
- Computer类
#include "CPU.h"
#include <iostream>
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::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;
}
- main函数
#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中的组合表示:
聚合
需求:
给计算机配一台音响。
- Computer类
#include "CPU.h"
#include "Computer.h"
#include <iostream>
#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; //音箱
};
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;
}
void Computer::addVoiceBox(VoiceBox *box) {
this->box = box;
}
Computer::~Computer()
{
std::cout << __FUNCTION__ << std::endl;
}
- main函数
#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
#include "Computer.h"
#include "VoiceBox.h"
using namespace std;
void test(VoiceBox *box) {
Computer a("intel", "i9", 1000, 8);
a.addVoiceBox(box);
}
int main(void) {
VoiceBox box;
test(&box);
system("pause");
return 0;
}
聚合不是组成关系,被包含的对象,也可能被其他对象包含。
拥有者,不需要对被拥有的对象的生命周期负责。
UML中的组合表示: