加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++多态实例之电脑组装

发布时间:2020-12-16 09:06:24 所属栏目:百科 来源:网络整理
导读:一个接口,可以使用不同的硬件。 #includeiostream using namespace std; class Cpu { public : virtual void calculate() = 0 ;}; VideoCard { void display() = Memory { void storage() = Computer { : Computer(Cpu * cpu,VideoCard* videoCard,Memory*

一个接口,可以使用不同的硬件。

#include<iostream>
using namespace std;

class Cpu {
public:
    virtual void calculate() = 0;
};
 VideoCard {
void display() =  Memory {
void storage() =  Computer {
:
    Computer(Cpu* cpu,VideoCard* videoCard,Memory* memory) {
        this->cpu = cpu;
        this->videoCard = videoCard;
        this->memory = memory;
    }
    void work() {
        cpu->calculate();
        videoCard->display();
        memory->storage();
    }
    ~Computer() {
        if (cpu != NULL) {
            delete cpu;
            cpu = NULL;
        }
        if (videoCard != NULL) {
            delete videoCard;
            videoCard =if (memory != NULL) {
            delete memory;
            memory = NULL;
        }
    }
private:
    Cpu* cpu;
    VideoCard* videoCard;
    Memory *memory;
};
class InterNetCpu : Cpu {
     calculate() {
        cout << "这是因特尔的cpu开始计算了" << endl;
    }
};
class InterNetVc : VideoCard {
     display() {
        cout << 这是因特尔的显卡开始显示了class InterNetMe : Memory {
     storage() {
        cout << 这是因特尔的内存条开始存储了class SamsungCpu :这是samsung的cpu开始计算了class SamsungVc :这是samsung的显卡开始显示了class SamsungMe :这是samsung的内存条开始存储了 test() {
    cout << -------第一批零件------- endl;
    Cpu* intelCpu = new InterNetCpu;
    VideoCard* intelVc =  InterNetVc;
    Memory* intelMe =  InterNetMe;
    //一台电脑
    Computer* computer =  Computer(intelCpu,intelVc,intelMe);
    computer->work();
    delete computer;
    cout << -------第二批零件------- endl;
    Cpu* samsungCpu =  SamsungCpu;
    VideoCard* samsungVc =  SamsungVc;
    Memory* samsungMe =  SamsungMe;
    Computer* computer2 = work();
    delete computer2;
}
int main() {
    test();
    system(pause");
    return ;
}

输出:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读