纯虚函数与抽象类

来源:互联网 发布:如何在淘宝上传照片 编辑:程序博客网 时间:2024/04/30 06:18
   1 #include <iostream>
      2 using namespace std;
      3 class Shape
      4 {
      5 protected:
      6     double x,y;
      7 public:
      8     void set(double i,double j)
      9     {
     10         x=i;y=j;
     11     }
     12     virtual void getArea() = 0;
     13 };
     14
     15 class Triangle:public Shape
     16 {
     17 public:
     18     void getArea()
     19     {
     20         cout<<"Triangle S = 1/2 * "<<x<<"*"
     21             <<y<<"="<<0.5*x*y<<endl;
     22     }
     23 };
     24
     25 class Rectangle:public Shape
     26 {
     27 public:
     28     void getArea()
     29     {
     30         cout<<"Rectangle S = * "<<x<<"*"
     31             <<y<<"="<<x*y<<endl;
     32     }
     33 };
     34
     35 int main()
     36 {
     37     Shape *p;
     38     Triangle t;
     39     Rectangle r;
     40
     41     p = &t;
     42     p->set(5.1,20.0);
     43     p->getArea();
     44
     45     p = &r;
     46     p->set(5.1,20.0);
     47     p->getArea();
     48     return 0;
     49 }

运行结果:[root@localhost dynamicBinding]# ./a.out
Triangle S = 1/2 * 5.1*20=51
Rectangle S = * 5.1*20=102

纯虚函数:1、基类中只声明不给出定义;声明格式如下:virtual 类型 函数名字(参数列表) = 0;
          2、具体实现在各个子类中,
          3、通过该基类指针或者引用就可以调用所有子类的虚函数
          4、基类只用于继承,仅仅作为一个接口;
          5、声明了纯虚函数的类就成为抽象类
注意:    1、不能声明抽象类的对象,但可以声明指向抽象类的指针变量和引用变量;
          2、抽象类中可以有多个纯虚函数
          3、抽象类中也可以定义其他非纯虚函数
          4、如果子类没有重新定义基类的纯虚函数,则子类必须将此虚函数声明为纯虚函数;
~                  
原创粉丝点击