如何在C++中实现动态多态性?

  • Post category:cplus

C++中的动态多态性是通过使用虚函数和指向对象的指针或引用实现的。

  1. 定义虚函数
    在基础类中定义虚函数,用于在派生类中进行覆写,实现动态多态性。在函数声明前加上virtual关键字,如:
class Base {
  public:
    virtual void virtualFunction() {
      std::cout << "This is the base virtual function." << std::endl;
    }
};
  1. 覆写虚函数
    在派生类中覆写虚函数,实现基础类与派生类之间的多态性。在函数声明前加上override关键字,如:
class Derived : public Base {
  public:
    void virtualFunction() override {
      std::cout << "This is the derived virtual function." << std::endl;
    }
};
  1. 使用指向对象的指针或引用调用虚函数
    通过使用基础类对象的指针或引用来调用虚函数,在运行时动态地选择调用哪个函数。如:
Base* ptr = new Derived();
ptr->virtualFunction();  // This is the derived virtual function.

完整的示例代码如下:

#include <iostream>

class Base {
  public:
    virtual void virtualFunction() {
      std::cout << "This is the base virtual function." << std::endl;
    }
};

class Derived : public Base {
  public:
    void virtualFunction() override {
      std::cout << "This is the derived virtual function." << std::endl;
    }
};

int main() {
  Base* ptr1 = new Base();
  Base* ptr2 = new Derived();

  ptr1->virtualFunction();  // This is the base virtual function.
  ptr2->virtualFunction();  // This is the derived virtual function.

  delete ptr1;
  delete ptr2;
  return 0;
}

另一个示例:

#include <iostream>

class Shape {
  public:
    virtual double getArea() {
      std::cout << "This is the base virtual function." << std::endl;
      return 0.0;
    }
};

class Circle : public Shape {
  private:
    double radius;

  public:
    Circle(double r) : radius(r) {}

    double getArea() override {
      std::cout << "This is the circle virtual function." << std::endl;
      return 3.14 * radius * radius;
    }
};

int main() {
  Shape* s = new Circle(1.0);
  std::cout << "Area: " << s->getArea() << std::endl;  // Area: 3.14
  return 0;
}

在上述示例中,圆形类覆写了基础类的getArea虚函数,用于计算圆形的面积。通过指向圆形类的对象指针,调用基础类的getArea函数,会动态调用圆形类的getArea函数,返回圆形的面积。