纯虚函数与抽象类

#include<iostream.h>
class shape 
{public:
  int a;
  shape(int t)
  {
      a=t;
  }
  virtual void area()=0;
};
class circle: public shape 
{
 public:
  void  area();
  circle(int x):shape(x){}
};
class square :public shape
{
 public:
 void area();
   square(int x):shape(x){}
};

void circle::area()
{
    cout<<"circle\n";
}

void square::area()
{
  cout<<"\nsquare\n";
}

void f(shape &h)
{h.area();
}
void main()
{
 circle objc(2);
 f(objc);
 cout<<objc.a;
 square objs(3);
 f(objs);
 cout<<objs.a<<endl;
}

//有纯虚函数的类就是抽象类
//虚函数可以实现多态,当然纯虚函数也可以!
//为什么要引入纯虚函数就是因为有些基类无需实现,只需在其子类实现即可,所以就引出纯虚函数与抽象类!

 

 

posted @ 2015-05-09 22:28  南哥的天下  阅读(166)  评论(0编辑  收藏  举报