C++多态

C++的多态依赖于类的继承和虚函数,它允许通过基类指针调用子类重写的函数,实现接口重用。纯虚函数在基类中定义,强制派生类提供实现,使得基类成为抽象类,不能实例化。
摘要由CSDN通过智能技术生成

c++多态

多态存在的前提是有类的继承。

当存在多个子类继承自父类时,这几个类都会有继承得来(同名的)的函数,调用函数时,根据具体调用的对象的不同来决定执行这几个同名函数中的哪一个的功能称为多态。


看一个未使用多态的反例:

#include <iostream> 
using namespace std;
 
class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Rectangle class area :" <<endl;
         return (width * height); 
      }
};
class Triangle: public Shape{
   public:
      Triangle( int a=0, int b=0):Shape(a, b) { }
      int area ()
      { 
         cout << "Triangle class area :" <<endl;
         return (width * height / 2); 
      }
};
// 程序的主函数
int main( )
{
   Shape *shape;
   Rectangle rec(10,7);
   Triangle  tri(10,5);
 
   // 存储矩形的地址
   shape = &rec;
   // 调用矩形的求面积函数 area
   shape->area();
 
   // 存储三角形的地址
   shape = &tri;
   // 调用三角形的求面积函数 area
   shape->area();
   
   return 0;
}

这段程序的输出是:

Parent class area
Parent class area

编译器将函数area()设置成了基类中的版本,函数的调用在程序执行之前就准备好了,area()函数在程序编译期间就已经设置好了。这是早绑定(Early binding)/静态绑定(Static binding)/编译时绑定(Compile-time binding)造成的结果,也称静态链接/静态多态 : 函数的调用,在编译器编译期间就可以确定函数的调用地址,并生产代码,是静态的,就是说地址是早绑定的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值