#include<iostream>
using namespace std;
class CPU
{
public:
virtual void calculate() = 0;
};
class VideoCard
{
public:
virtual void display() = 0;
};
class Memory
{
public:
virtual void storage() = 0;
};
//--------- Computer ----------
class Computer
{
public:
Computer(CPU* cpu, VideoCard* vc, Memory* mem)
{
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
void doWork()
{
m_cpu->calculate();
m_vc->display();
m_mem->storage();
}
//析构函数
~Computer()
{
if (m_cpu != NULL)
{
delete m_cpu;
m_cpu = NULL;
}
if (m_vc != NULL)
{
delete m_vc;
m_vc = NULL;
}
if (m_mem != NULL)
{
delete m_mem;
m_mem = NULL;
}
}
private:
CPU* m_cpu;
VideoCard* m_vc;
Memory* m_mem;
};
//--------- Intel -----------
class IntelCPU :public CPU
{
public:
virtual void calculate()
{
cout << "Intel的CPU开始计算了!" << endl;
}
};
class IntelVideoCard :public VideoCard
{
public:
virtual void display()
{
cout << "Intel的显卡开始显示了" << endl;
}
};
class IntelMemory:public Memory
{
public:
virtual void storage()
{
cout << "Intel的内存条" << endl;
}
};
///
//---------- Lenovo ------------
class LenovoCPU :public CPU
{
public:
virtual void calculate()
{
cout << "Lenovo的CPU开始计算了!" << endl;
}
};
class LenovoVideoCard :public VideoCard
{
public:
virtual void calculate()
{
cout << "Lenovo的显卡开始显示了" << endl;
}
};
class LenovoMemory :public Memory
{
public:
virtual void calculate()
{
cout << "Lenovo的内存条" << endl;
}
};
void test01()
{
//第一台电脑零件
CPU* intelCpu = new IntelCPU;
VideoCard* intelCard = new IntelVideoCard;
Memory* intelMem = new IntelMemory;
//第一台电脑
Computer* computer1 = new Computer(intelCpu, intelCard, intelMem);
computer1->doWork();
delete computer1;
}
int main()
{
test01();
}
多态--电脑组装具体实现
最新推荐文章于 2024-05-20 17:41:38 发布