DW做旅游網(wǎng)站模板正規(guī)拉新推廣平臺有哪些
案例:小明打算買兩臺組裝電腦,假設(shè)電腦零部件包括CPU、GPU和內(nèi)存組成。
一臺電腦使用intel的CPU、GPU和內(nèi)存條
一臺電腦使用Huawei的CPU、GPU和Intel的內(nèi)存條
分析:使用多態(tài)進(jìn)行實現(xiàn)
將CPU、GPU和內(nèi)存條定義為抽象類,內(nèi)部分別定義其對應(yīng)功能的純虛函數(shù)
Intel的CPU繼承CPU,并實現(xiàn)其內(nèi)部的純虛函數(shù)(calculate)
Intel的GPU繼承GPU,并實現(xiàn)其內(nèi)部的純虛函數(shù)(display)
Intel的MEMORY繼承MEMORY,并實現(xiàn)其內(nèi)部的純虛函數(shù)(memory)
同樣華為也一樣繼承CPU、GPU和MEMORY并實現(xiàn)對應(yīng)的純虛函數(shù)
封裝一個Computer類,包含CPU、GPU和MEMORY,其成員屬性為CPU、GPU和MEMORY的指針
內(nèi)部有個work方法,用于調(diào)用CPU、GPU和MEMORY對應(yīng)的方法
最后小明通過Computer類進(jìn)行組裝自己的電腦,并運(yùn)行
#include<iostream>
class CPU
{
public:virtual void calculate() = 0;
};class GPU
{
public:virtual void display() = 0;
};class MEMORY
{
public:virtual void memory() = 0;
};class Computer
{
public:Computer(CPU *cpu,GPU *gpu,MEMORY *memory){m_cpu = cpu;m_gpu = gpu;m_memory = memory;}void work() {m_cpu->calculate();m_gpu->display();m_memory->memory();}~Computer(){if (m_cpu != NULL) {delete m_cpu;m_cpu = NULL;}if (m_gpu != NULL){delete m_gpu;m_gpu = NULL;}if (m_memory != NULL){delete m_memory;m_memory = NULL;}}private:CPU *m_cpu;GPU *m_gpu;MEMORY *m_memory;
};class IntelCPU :public CPU
{
public:virtual void calculate(){std::cout << "IntelCPU is calculate..." << std::endl;}
};
class IntelGPU :public GPU
{
public:virtual void display(){std::cout << "IntelGPU is display..." << std::endl;}
};
class IntelMEMORY :public MEMORY
{
public:virtual void memory(){std::cout << "IntelMEMORY is memory..." << std::endl;}
};class HuaweiCPU :public CPU
{
public:virtual void calculate(){std::cout << "HuaweiCPU is calculate..." << std::endl;}
};
class HuaweiGPU :public GPU
{
public:virtual void display(){std::cout << "HuaweiGPU is display..." << std::endl;}
};
class HuaweiMEMORY :public MEMORY
{
public:virtual void memory(){std::cout << "HuaweiMEMORY is memory..." << std::endl;}
};int main(int argc,char **argv)
{CPU *my_CPU = new IntelCPU;GPU *my_GPU = new IntelGPU;MEMORY *my_memory = new IntelMEMORY;Computer *my_computer = new Computer(my_CPU, my_GPU, my_memory);my_computer->work();delete my_computer;Computer* my_computer_2 = new Computer(new HuaweiCPU,new HuaweiGPU,new IntelMEMORY);my_computer_2->work();return 0;
}
運(yùn)行效果: