21xrx.com
2025-06-15 12:48:44 Sunday
文章检索 我的文章 写文章
C++虚函数的实例说明
2023-07-11 13:00:08 深夜i     17     0
C++ 虚函数 实例

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()
     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;
  shape->area();
  shape = &tri;
  shape->area();
 
  return 0;
}

在上面的示例中,Shape类是基类,并包含一个名为“area”的虚函数。 Rectangle和Triangle类都是Shape的派生类,并且都对虚函数进行了覆盖重写。在main函数中,分别创建了Rectangle和Triangle的对象,并使用基类指针shape分别指向这两个对象。

在调用shape->area()时,根据指针的实际类型(即所指向对象的派生类)决定调用哪个类的函数。Rectangle类的area函数输出“Rectangle class area:”,而Triangle类的area函数输出“Triangle class area:”。

通过这个示例,可以看到使用虚函数可以实现多态性,并具有更灵活的代码实现。

  
  

评论区