#include <iostream>

// CPU基类
class CPU {
public:
    virtual ~CPU() {}
    virtual void process() = 0;
};

// GPU基类
class GPU {
public:
    virtual ~GPU() {}
    virtual void render() = 0;
};

// RAM基类
class RAM {
public:
    virtual ~RAM() {}
    virtual void storage() = 0;
};

// 英特尔CPU子类
class InterCpu : public CPU {
public:
    void process() override {
        std::cout << "Intel CPU is processing." << std::endl;
    }
};

// 英特尔GPU子类
class InterGpu : public GPU {
public:
    void render() override {
        std::cout << "Intel GPU is rendering." << std::endl;
    }
};

// 英特尔RAM子类
class InterRam : public RAM {
public:
    void storage() override {
        std::cout << "Intel RAM is storing data." << std::endl;
    }
};

// 联想CPU子类
class LenovoCpu : public CPU {
public:
    void process() override {
        std::cout << "Lenovo CPU is processing." << std::endl;
    }
};

// 联想GPU子类
class LenovoGpu : public GPU {
public:
    void render() override {
        std::cout << "Lenovo GPU is rendering." << std::endl;
    }
};

// 联想RAM子类
class LenovoRam : public RAM {
public:
    void storage() override {
        std::cout << "Lenovo RAM is storing data." << std::endl;
    }
};

// 组装电脑类
class Computer {
public:
    // Computer(CPU* cpu, GPU* gpu, RAM* ram) {
    // m_cpu = cpu;
    // m_gpu = gpu;
    // m_ram = ram;
    // }
    // 第二种写法
    Computer(CPU* cpu, GPU* gpu, RAM* ram) : m_cpu(cpu), m_gpu(gpu), m_ram(ram) {}

    void work() {
        m_cpu->process();
        m_gpu->render();
        m_ram->storage();
    }

    ~Computer() {
        delete m_cpu;
        delete m_gpu;
        delete m_ram;
    }

private:
    CPU* m_cpu;
    GPU* m_gpu;
    RAM* m_ram;
};

int main() {
    Computer* c1 = new Computer(new InterCpu(), new InterGpu(), new InterRam());
    c1->work();
    delete c1; // 这里会释放c1并且调用Computer的析构函数,从而释放new InterCpu, new InterGpu, new InterRam
    return 0;
}
11-26 05:22