黑马程序员C++教程从0到1入门编程60类与对象--多态案例子3电脑组装具体案例
c++中使用多态实现电脑组装具体案例
例子
#include <iostream>
#include<string>
using namespace std;
#if 1
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*video, memory*menory)
{
a = cpu;
b = video;
c = menory;
}
~computer()
{
if (a != NULL)
{
delete a;
a = NULL;
}
if (b != NULL)
{
delete b;
b = NULL;
}
if (c != NULL)
{
delete c;
c = NULL;
}
}
void work()
{
a->calculate();
b->display();
c->storage();
}
private:
cpu *a;
videocard*b;
memory*c;
};
class intelcpu :public cpu
{
virtual void calculate()
{
cout << "intel的cpu开始计算啦" << endl;
}
};
class intelvedio :public videocard
{
virtual void display()
{
cout << "intel的显卡开始计算啦" << endl;
}
};
class intelmem :public memory
{
virtual void storage()
{
cout << "intel的内存条开始计算啦" << endl;
}
};
class lenovocpu :public cpu
{
virtual void calculate()
{
cout << "lenovo的cpu开始计算啦" << endl;
}
};
class lenovovedio :public videocard
{
virtual void display()
{
cout << "lenovo的显卡开始计算啦" << endl;
}
};
class lenovomem :public memory
{
virtual void storage()
{
cout << "lenovo的内存条开始计算啦" << endl;
}
};
void test01()
{
cpu*intcpu = new intelcpu;
videocard*intelvideocard = new intelvedio;
memory*menory = new intelmem;
computer *conputer1=new computer(intcpu, intelvideocard, menory);
conputer1->work();
delete conputer1;
computer *conputer2 = new computer(new lenovocpu, new lenovovedio, new lenovomem);
conputer2->work();
delete conputer2;
}
#endif
int main()
{
test01();
system("pause");
return 0;
}