组合与聚合对比:
组合: 同生共死 ( 生命周期一致 )
聚合: 有聚有散 ( 生命周期随分配 )
一.Computer与Cpu组合
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BuKQtZTc-1587262856672)(file:///C:\Users\Dell\AppData\Local\Temp\ksohtml23044\wps1.jpg)]
Computer.h
#pragma once
#include <iostream>
using namespace std;
#include "Cpu.h"//include组合拥有的类的头文件
class VoiceBox;//声明提及的类
class Computer{
public:
Computer();
Computer(int hardDisk, int memory, const char* cpuBrand, const char* cpuVersion);
~Computer();
void addVoiceBox(VoiceBox* box);
private:
Cpu cpu;//组合拥有的类的对象
//Cpu* cpu;不推荐用指针,因为数量确定,不必动态分配(动态分配还需要为防内存泄漏,另写拷贝赋值构造,麻烦)
//Cpu* cpu2;若数量不定,应使用指针动态分配
VoiceBox* box;//聚合的对象指针,可以不初始化,因为不一定聚合,若聚合一定要给地址
int hardDisk;
int memory;
};
Computer.cpp
#include "Computer.h"
Computer::Computer():cpu() {//若函数参数都为默认参数,那么可以不写任何参数
//Computer::Computer(){不推荐用指针对象
this->hardDisk = 0;
this->memory = 0;
cout << __FUNCTION__ << endl;
//this->cpu = new Cpu();不推荐用指针对象
//this->cpu2 = new Cpu();
}
Computer::Computer(int hardDisk, int memory, const char* cpuBrand, const char* cpuVersion):cpu(cpuBrand, cpuVersion){
//Computer::Computer(int hardDisk, int memory, const char* cpuBrand, const char* cpuVersion){不推荐用指针对象
this->hardDisk = hardDisk;
this->memory = memory;
cout << __FUNCTION__ << endl;
//this->cpu = new Cpu(cpuBrand,cpuVersion);不推荐用指针对象
//this->cpu2 = new Cpu(cpuBrand,cpuVersion);不推荐用指针对象
}
Computer::~Computer() {
//要delete也只能delete自己拥有的
//delete cpu;不推荐用指针对象
//delete cpu2;不推荐用指针对象
cout << __FUNCTION__ << endl;
}
void Computer::addVoiceBox(VoiceBox *box) {
this->box = box;
}
Cpu.h
#pragma once
#include <iostream>
using namespace std;
class Cpu{
public:
//Cpu(char *brand="dell", int version= 2);×-记得用const类型-因默认参数为const类型
Cpu(const char* brand = "dell", const char* version = "xps");
~Cpu();
private:
string brand;
string version;
};
Cpu.cpp
#include "Cpu.h"
Cpu::Cpu(const char* brand, const char* version) {//默认值在实现部分不写
this->brand = brand;//brand若为char*型则此等式无法成立
this->version = version;
cout << __FUNCTION__ << endl;
}
Cpu::~Cpu() {
cout << __FUNCTION__ << endl;
}
二.Computer与VoiceBox聚合
VoiceBox.h
#pragma once
#include <iostream>
using namespace std;
class VoiceBox
{
public:
VoiceBox();
~VoiceBox();
};
VoiceBox.cpp
#include "VoiceBox.h"
VoiceBox::VoiceBox() {
cout << __FUNCTION__ << endl;
}
VoiceBox::~VoiceBox() {
cout << __FUNCTION__ << endl;
}
三.测试文件与打印效果
#include "Computer.h"
#include "VoiceBox.h"//因不是拥有关系,所以在main中还要加上聚合的类的头文件
void testCombination() {
Computer a;//注意不要自己乱搞在后面加括号,加括号代表调用带参函数的默认值
//Computer a();×
}
void testAggregate(VoiceBox* box) {
Computer a;
a.addVoiceBox(box);
}//在块末尾Computer与Cpu共死
int main(){
cout << "------1.组合------" << endl;
testCombination();
cout << "------2.聚合------" << endl;
VoiceBox box;
testAggregate(&box);
system("pause");//也可cout<<"end"<<endl;
//int main函数可以不写返回值;也可写void main
}//在块末尾VoiceBox才析构
"------2.聚合------" << endl;
VoiceBox box;
testAggregate(&box);
system("pause");//也可cout<<"end"<<endl;
//int main函数可以不写返回值;也可写void main
}//在块末尾VoiceBox才析构