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

2020-08-26 16:01:52 浏览数 (1)

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

代码语言:javascript复制
#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;
}

输出:

0 人点赞