c++中的抽象类(纯虚函数)

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、派生类中必须实现抽象类中的纯虚函数,否则它仍将被看作一个抽象类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值