Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7553499
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: C/C++

2011-03-31 10:51:33

  1. /****************************************************************************************
  2. * 文件名:
  3. * 功能:纯虚函数和抽象类简单应用
  4. * 说明:纯虚函数在基类中不用定义该函数,它的实现部分,即函数体在各派生类中完成。
  5.         包含一个或多个纯属函数的类称为抽象类,抽象类不能定义对象,但可以声明抽象类的指针。
  6. * 时间:2011-3-31                                                   --Lzy
  7. *****************************************************************************************/
  8. //纯属函数应用

  9. #include <iostream.h>

  10. class CPoint        //抽象基类

  11. {
  12. protected:
  13.     long x, y;

  14. public:
  15.     CPoint(int xx = 0, int yy = 0){x = xx; y = yy;}        
  16.     virtual void display() = 0;            //纯虚函数成员

  17. };

  18. class CRctangle:public CPoint
  19. {
  20. private:
  21.     double width, height;

  22. public:
  23.     CRctangle(long x, long y, long w, long h):CPoint(x, y){width = w; height = h;}
  24.     void display()
  25.     {
  26.         cout<<"矩形"<<endl;
  27.         cout<<"位置:("<<x<<","<<y<<")"<<endl;
  28.         cout<<"长 = "<<width<<" 宽 = "<<height<<endl;
  29.     }
  30. };

  31. class CTriangle:public CPoint
  32. {
  33. private:
  34.     double a,b,c;

  35. public:
  36.     CTriangle(long x, long y, long a1, long b1, long c1):CPoint(x, y)
  37.     {a = a1; b = b1; c = c1;}

  38.     void display()
  39.     {
  40.         cout<<"三角形"<<endl;
  41.         cout<<"位置:("<<x<<","<<y<<")"<<endl;
  42.         cout<<"三边长"<<a<<" "<<b<<" "<<c<<endl;
  43.     }
  44. };

  45. void main()
  46. {
  47.     CPoint *ptr[2];            //声明抽象基类指针

  48.     CRctangle r1(10,10,120,60);
  49.     CTriangle t1(50,50,345,456,567);

  50.     ptr[0] = &r1;            //指针指向 r1对象

  51.     ptr[0]->display();

  52.     ptr[1] = &t1;            //指针指向 t1对象

  53.     ptr[1]->display();
  54. }
阅读(1848) | 评论(0) | 转发(2) |
0

上一篇:虚函数简单应用

下一篇:模板简单应用

给主人留下些什么吧!~~