1、在基类中不能给出有意义的虚函数定义,这时可以把它说明成纯虚函数,把它的定义留给派生类来做
2、定义纯虚函数:
class 类名{
virtual 返回值类型 函数名(参数表) = 0;
};
3、纯虚函数不需要实现
#include <iostream>
#include<vector>
using namespace std;
class Shape
{
public:
virtual void Draw()=0;
virtual ~Shape()//如果不是纯虚函数,则派生类析构函数不能执行,会造成内存泄漏问题
{
cout<<"~Shape().........."<<endl;
}
};
class Circle:public Shape
{
public:
void Draw()
{
cout<<"Circle::Draw().........."<<endl;
}
~Circle(){
cout<<"~Circle().........."<<endl;
}
};
class Square:public Shape
{
public:
void Draw()
{
cout<<"Square::Draw().........."<<endl;
}
~Square()
{
cout<<"Square::~Square().........."<<endl;
}
};
class Retangle:public Shape
{
public:
void Draw()
{
cout<<"Square::Retangle().........."<<endl;
}
~Retangle()
{
cout<<"Retangle::~Retangle().........."<<endl;
}
protected:
private:
};
void DrawAllShape(vector<Shape*> v)
{
vector<Shape*>::const_iterator it;
for (it=v.begin();it!=v.end();++it)
{
Shape* s=(*it);
s->Draw();
}
}
void DeleteAllShape(vector<Shape*> v)
{
vector<Shape*>::const_iterator it;
for (it=v.begin();it!=v.end();++it)
{
delete (*it);
}
}
//
class ShapeFactory
{
public:
static Shape* CreateFactory(const string& name){
Shape *ps=0;
if (name.compare("Circle"))
{
ps=new Circle;
}
else if(name.compare("Square"))
{
ps=new Square;
}else if (name.compare("Retangle"))
{
ps=new Retangle;
}
return ps;
}
protected:
private:
};
int main()
{
// Shape s; error ,抽象类不能实例化
//Circle c;
//c.Draw();
Shape* ps;
vector<Shape*> ve;
/* ps=new Circle;
ve.push_back(ps);
ps=new Square;
ve.push_back(ps);
ps=new Retangle;
ve.push_back(ps);*/
ps=ShapeFactory::CreateFactory("Circle");
ve.push_back(ps);
ps=ShapeFactory::CreateFactory("Square");
ve.push_back(ps);
ps=ShapeFactory::CreateFactory("Retangle");
ve.push_back(ps);
DrawAllShape(ve);
DeleteAllShape(ve);
return 0;
}
//1、抽象类只能作为基类来使用
//2、不能声明为抽象类的对象
//3、构造函数不能是虚函数,析构函数可以是虚函数
//4、抽象类不能用于直接创建对象实例
//5、可使用指向抽象类的指针支持运行时多态性
//6、派生类中必须实现抽象类中的纯虚函数,否则它仍将被看作一个抽象类