<>多态案例–组装三台电脑

* 电脑零件基类CPU,显卡,内存条
* 不同的厂商,如Intel,Lenovo等;
* 三个零件基类,CPU,Videocard,Memory;不同厂商生产的零件来实现具体的功能。 #include <iostream> using
namespace std; //公共零件基类 class CPU { public: virtual void calculate() = 0; };
class Videocare { public: virtual void display() = 0; }; class Memory { public:
virtual void storage() = 0; }; //Intel生产的零件 class IntelCPU : public CPU { public
: virtual void calculate() { cout << "IntelCPU is calculating\n"; } }; class
IntelVideocard : public Videocare { public: virtual void display() { cout <<
"Intel Videocard is displaying\n"; } }; class IntelMemory : public Memory {
public: virtual void storage() { cout << "Intel Memory is storaging\n"; } };
//Lenovo生产的零件 class LenovoCPU : public CPU { public: virtual void calculate() {
cout<< "LenovoCPU is calculating\n"; } }; class LenovoVideocard : public
Videocare{ public: virtual void display() { cout << "Lenovo Videocard is
displaying\n"; } }; class LenovoMemory : public Memory { public: virtual void
storage() { cout << "Lenovo Memory is storaging\n"; } }; //电脑组装 class Computer {
private: CPU* cpu; Videocare* vc; Memory* memory; public: Computer(CPU* cpu,
Videocare* vc, Memory* memory) { this->cpu = cpu; this->vc = vc; this->memory =
memory; } ~Computer() { if (cpu != NULL) { delete cpu; cpu = NULL; } if (cpu !=
NULL) { delete cpu; cpu = NULL; } if (cpu != NULL) { delete cpu; cpu = NULL; } }
void work() { cpu->calculate(); vc->display(); memory->storage(); } }; //组装测试
//测试Intel零件 void test1() { CPU* intelCpu = new IntelCPU; Videocare* intelVc =
new IntelVideocard; Memory* memory = new IntelMemory; Computer computer(intelCpu
, intelVc, memory); computer.work(); } //测试Lenovo零件 void test2() { Computer
computer(new LenovoCPU, new LenovoVideocard, new LenovoMemory); computer.work();
} void test3() { Computer computer(new IntelCPU, new IntelVideocard, new
LenovoMemory); computer.work(); } int main() { cout <<
"------------测试1开始-----------\n"; test1(); cout <<
"------------测试2开始-----------\n"; test2(); cout <<
"------------测试3开始-----------\n"; test3(); return 0; }

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信