C++中虚函数、纯虚函数和多态的关系

虚函数、纯虚函数和多态的关系如下:

  1. 虚函数是指在父类中被声明为虚函数的函数,在子类中可以被重写,用于实现多态性。
  2. 纯虚函数是一种特殊的虚函数,它没有实现体,只有声明,它的存在是为了让子类去重写它,使得实现多态性。
  3. 多态是指同一个函数在不同的对象上有着不同的行为,通过虚函数和继承实现。在父类中通过声明函数为虚函数,子类在继承时可以覆盖父类的同名函数,从而实现多态效果。

下面是相应的CPP代码:

#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() {
    
    
         cout << "父类的 area :" <<endl;
         return 0;
      }
};

class Rectangle: public Shape {
    
    
   public:
      Rectangle(int a = 0, int b = 0):Shape(a, b) {
    
     }
      // 派生类的虚函数 重写父类的虚函数 实现多态
      int area() {
    
    
         cout << "Rectangle 的 area :" << width * height << endl;
         return (width * height);
      }
};

class Triangle: public Shape {
    
    
   public:
      Triangle(int a = 0, int b = 0):Shape(a, b) {
    
     }
      // 派生类的虚函数 重写父类的虚函数 实现多态
      int area() {
    
    
         cout << "Triangle 的 area :" << width * height / 2 << 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;
}

在这个代码示例中,我们创建了一个Shape基类,它有一个虚函数area,两个派生类RectangleTriangle,它们都重写了该函数以实现多态,然后在main()函数中创建了一个Shape类型的指针,用于存储Rectangle对象和Triangle对象的地址,然后分别调用它们的area()函数,从而实现多态性。

猜你喜欢

转载自blog.csdn.net/qq_39506862/article/details/130893849