一个例子理解虚函数,类和对象

#include <iostream>
using namespace std;
#include <string>

class CPU
{
public:
    virtual void calculate() = 0;
};

class VideoCard
{
public:
    virtual void display() = 0;
};

class Memory
{
public:
    virtual void storage() = 0;
};

class IntelCPU :public CPU
{
public:
    void calculate() {
        cout << "intel的CPU开始计算" << endl;
    }
};

class IntelVideoCard :public VideoCard
{
public:
    void display() {
        cout << "intel的显卡开始显示" << endl;
    }
};
class IntelMemory :public Memory
{
public:
    void storage() {
        cout << "intel的内存开始存储" << endl;
    }
    
};

class AmdCPU :public CPU
{
public:
    void calculate() {
        cout << "Amd的CPU开始计算" << endl;
    }
};

class AmdVideoCard :public VideoCard
{
public:
    void display() {
        cout << "Amd的显卡开始显示" << endl;
    }
};
class AmdMemory :public Memory
{
public:
    void storage() {
        cout << "Amd的内存开始存储" << endl;
    }

};

class Computer
{
public:
    Computer(CPU *cpu,VideoCard *vc, Memory *mem) {
        m_cpu = cpu;
        m_mem = mem;
        m_vc = vc;
    }
public:
    void work() {
        m_cpu->calculate();
        m_mem->storage();
        m_vc->display();
    }

    ~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;
};

void test01()
{
    CPU *intelcpu = new IntelCPU;
    VideoCard *intelvc = new IntelVideoCard;
    Memory *intelmem = new IntelMemory;
    Computer *computer1 = new Computer(intelcpu, intelvc, intelmem);
    cout << "---------------------第一台电脑开始工作---------------------" << endl;
    computer1->work();

    delete computer1;
}

void test02()
{
    CPU *amdcpu = new AmdCPU;
    VideoCard *amdvc = new AmdVideoCard;
    Memory *amdmem = new AmdMemory;
    Computer *computer2 = new Computer(amdcpu, amdvc, amdmem);
    cout << "---------------------第二台电脑开始工作---------------------" << endl;
    computer2->work();

    delete computer2;
}

int main()
{
    test01();
    test02();

    system("pause");
    return 0;
}
本文作者:Author:     文章标题:一个例子理解虚函数,类和对象
本文地址:https://www.ningcaichen.top/archives/160.html     
版权说明:若无注明,本文皆为“宁采晨's Blog”原创,转载请保留文章出处。
Last modification:2020 年 04 月 16 日 04 : 00 AM

Leave a Comment

召唤看板娘