20191230 C++组合、聚合的用法

1、需求:
构建一个计算机类,一台计算机,由CPU芯片,硬盘,内存等组成。
CPU芯片也使用类来表示。
-----根据分析。CPU是计算机的一部分,属于组合用法。
2、需求
给计算机配一台音响。
–根据分析,音响和计算机是聚合关系。

//cpu.h
#pragma once
class cpu
{
public:
	cpu(const char* brand="intel",const char* version="6i");
	~cpu();
private:
	const char* brand;
	const char* version;

};
///***********************cpu.CPP************************
#include "cpu.h"
#include <iostream>
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.h************************
#pragma once
#include "cpu.h"
#include "voiceBox.h"

class computer
{
public:
	computer(const char* brand,const char* version,int disk,int memory);
	~computer();
	void addVoiceBox(voiceBox* box);

private:
	cpu CPU;
	int disk;//硬盘大小,单位G
	int memory;//内存条大小,单位G
	voiceBox* box;

};
//*********************computer.cpp**************************
#include "computer.h"
#include <iostream>
computer::computer(const char* brand, const char* version, int disk, int memory): CPU(brand,version)//第二种方式,更简洁
{
	this->disk = disk;
	this->memory = memory;
	//this->CPU = cpu(brand, version);//这是其中的一种初始化方式

	std::cout << __FUNCTION__ << std::endl;
}

computer::~computer() {
	std::cout << __FUNCTION__    << std::endl;
	std::cout << __TIME__ << std::endl;
	std::cout << __DATE__ << std::endl;
	std::cout << __FILE__ << std::endl;
	std::cout << __LINE__ << std::endl;
}

void computer::addVoiceBox(voiceBox* box) {
	this->box = box;
}
//***********************main.cpp****************************
#include <Windows.h>
#include<string>
#include "computer.h"
#include "voiceBox.h"

void test(voiceBox* box) {
	computer myCompuetr("interl","i9",4000,32);
	myCompuetr.addVoiceBox(box);
}
int main() {
	voiceBox box;

	test(&box);

	system("pause");
	return 0;
}
//*******************voiceBox.h*************************
#pragma once
class voiceBox
{
public: 
	voiceBox();
	~voiceBox();
private:
};
//*********************voiceBox.cpp**************************
#include "voiceBox.h"
#include<iostream>
voiceBox::voiceBox() {
	std::cout << __FUNCTION__ << std::endl;
}
voiceBox::~voiceBox() {
	std::cout << __FUNCTION__ << std::endl;
}

运行结果如图:在这里插入图片描述

发布了51 篇原创文章 · 获赞 0 · 访问量 527

猜你喜欢

转载自blog.csdn.net/weixin_40071289/article/details/103761756
今日推荐