纯虚函数与抽象类

   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、如果子类没有重新定义基类的纯虚函数,则子类必须将此虚函数声明为纯虚函数;
~                  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值