首页 > 编程语言 > 详细

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

时间:2019-12-26 17:07:53      阅读:78      评论:0      收藏:0      [点我收藏+]

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

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

输出:

技术分享图片

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

原文:https://www.cnblogs.com/xiximayou/p/12102653.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!