C/C++教程

c++封装继承多态实例

本文主要是介绍c++封装继承多态实例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <iostream>
#include <string>
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 *cc ,VideoCard *vv,Memory *mm)
    {


        c=cc;
        v=vv;
        m=mm;
      

    }
    void dowork()
    {
        c->calculate();
        m->storage();
        v->display();
    }

    ~Computer()
    {


       if (c!=NULL){
           delete c;
           c=NULL;
       }
       if (m!=NULL){
           delete m;
           m=NULL;
       }
       if (v!=NULL){
           delete v;
           v=NULL;
       }
      

    }
private:
    CPU *c;
    VideoCard *v;
    Memory *m;
};
class InterCpu :public CPU
{
    void calculate()
    {
        cout<<"inter的cpu工作了"<<endl;
    }
};
class NvidiaVideoCard:public VideoCard
{
    public:
    void display()
    {
        cout <<"英伟达的显卡工作了"<<endl;
    }
};
class SanXingMemory:public Memory
{
    public:
    void storage()
    {
        cout <<"三星内存条工作了"<<endl;
    }
};
void test01()
{
   CPU *interCPU=new InterCpu;
   VideoCard *NvidiaCard=new NvidiaVideoCard;
   Memory *OneMemory=new SanXingMemory;
   Computer *computer1= new Computer(interCPU,NvidiaCard,OneMemory);
   computer1->dowork();
   delete computer1;

}
int main()
{

    // 创建圆


    test01();
    system("pause");
    return 0; 
}



这篇关于c++封装继承多态实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!