多态性指的是通过类的继承关系,在不同的对象上调用同一成员函数时,可以产生不同的结果。它是 C++ 中的一种强大的特性,可以让程序更加灵活和可扩展。
以下是一个简单的 C++ 多态性实例,我们可以通过继承和虚函数来实现:
#include <iostream>  
using namespace std;
// 基类
class Shape {
   
   protected:
      int width, height;
   public:
      Shape( int a = 0, int b = 0) {
   
         width = a;
         height = b;
      }
      // 纯虚函数
      virtual int area() = 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
   cout << shape->area() << endl;
   // 存储三角形的地址
   shape = &tri;
   // 调用三角形的求面积函数 area
   cout << shape->area() << endl;
   return 0;
}
上述代码中,我们定义了一个基类Shape和两个派生类Rectangle和Triangle。Shape 类中的 area() 函数是一个纯虚函数,它的实现在派生类中完成。纯虚函数的声明格式如下所示:
virtual int area() = 0;
我们可以看到,它没有定义任何的功能实现。在派生类中需要定义该函数的功能实现。在上面的程序中,派生类 Rectangle 和 Triangle 分别对基类中的 area() 函数进行了实现。
当我们调用 area() 函数时,程序会根据对象的类型调用相应子类中的 area() 函数,从而产生不同的结果。
我来详细解释一下它的原理:
- 首先定义了抽象基类 Shape,并在其中声明了纯虚函数 area()。
- 然后定义了两个派生类 Rectangle 和 Triangle,它们都重新定义了 area() 函数,并根据自己的特点实现了对应的 area() 函数。
- 在程序主函数中,分别创建了一个 Rectangle 对象和 Triangle 对象,用基类指针 shape 分别指向它们,并调用了它们的 area() 函数。
- 当调用 shape->area() 时,程序会根据 shape 指向的对象是 Rectangle 对象还是 Triangle 对象,来决定调用哪个 area() 函数,从而产生不同的结果。
我们可以通过输出结果来证明它的效果:
Rectangle class area :
70
Triangle class area :
25
从输出结果可以看出,程序调用了不同的 area() 函数,并产生了不同的结果,这就是多态性的实现。
