#include <iostream>
using namespace std;
class cpu{
public:
virtual void cupwork()=0;
};
class displaycard{
public:
virtual void displaycardwork()=0;
};
class memory{
public:
virtual void memorywork()=0;
};
class computer{
public:
computer(cpu*cpu,displaycard*dpd,memory*mem)
{
c_cpu=cpu;
c_dpd=dpd;
c_mem=mem;
}
void dowork()
{
c_cpu->cupwork();
c_dpd->displaycardwork();
c_mem->memorywork();
}
~computer()
{
if(c_cpu!=NULL)
{
delete c_cpu;
c_cpu=NULL;
}
if(c_dpd!=NULL)
{
delete c_dpd;
c_dpd=NULL;
}
if(c_mem!=NULL)
{
delete c_mem;
c_mem=NULL;
}
}
private:
cpu *c_cpu;
displaycard *c_dpd;
memory *c_mem;
};
//厂商
//inter
class intercpu:public cpu{
public:
virtual void cupwork()
{
cout<<"intercpu开始工作"<<endl;
}
};
class interdisplaycard:public displaycard{
public:
virtual void displaycardwork()
{
cout<<"inter显卡开始工作"<<endl;
}
};
class intermemory:public memory{
public:
virtual void memorywork()
{
cout<<"inter内存开始工作"<<endl;
}
};
//联想
class Lenovocpu:public cpu{
public:
virtual void cpuwork()
{
cout<<"Lenovocpu开始工作"<<endl;
}
};
class Lenovodisplaycard:public displaycard{
public:
virtual void displaycardwork()
{
cout<<"Lenovo显卡开始工作"<<endl;
}
};
class Lenovomemory:public memory{
public:
virtual void memorywork()
{
cout<<"Lenovo内存条开始工作"<<endl;
}
};
void test()
{
cpu*intercpu=new intercpu;
displaycard*interdisplaycard=new interdisplaycard;
memory*intermemory=new intermemory;
computer*computer=new computer(intercpu,interdisplaycard,intermemory);
computer->dowork();
delete computer;
}
int main()
{
test();
system("pause");
return 0;
}
错误如图
纯虚函数是 一种特殊的虚函数,它的一般格式如下: class <类名> { virtual <类型><函数名>(<参数表>)=0; … }; 在许多情况下,在基类中不能对虚函数给出有意义的实现,而把它声明为纯虚函数,它的实现留给该基类的派生类去 做。这就是纯虚函数的作用。 纯虚函数可以让类先具有一个操作名称,而没有操作内容,让派生类在继承时再去具体地给出定义。 凡是含有纯虚函数的类叫做抽象类。这种类不能声明对象,只是作为基类为派生类服务。除非在派生类中完全实现基类中所有的的纯虚函数,否则,派生类也变成了 抽象类,不能实例化对象。
new的时候需要static cast或者c方式强转类型