C++ 虚拟函数与虚继承:揭示多重继承中的复杂性
虚拟函数
虚拟函数是 C++ 中一种特殊类型的成员函数,允许派生类重写基类中的函数。当基类指针或引用指向派生类对象时,将会调用派生类的虚拟函数。
class Shape { public: virtual double area() const = 0; // 纯虚函数 }; class Rectangle : public Shape { public: Rectangle(double width, double height) : m_width(width), m_height(height) {} double area() const override { return m_width * m_height; } // 重写虚函数 private: double m_width; double m_height; };
虚继承
虚继承是一种技术,用于解决多重继承中发生的菱形继承问题(也称为多重继承的歧义性)。
class Animal { public: virtual void speak() const { cout << "Animal speaks" << endl; } }; class Dog : virtual public Animal { // 虚继承 public: void speak() const override { cout << "Dog barks" << endl; } }; class Cat : virtual public Animal { // 虚继承 public: void speak() const override { cout << "Cat meows" << endl; } }; class SiberianHusky : public Dog, public Cat { // 多重继承 public: void speak() const override { cout << "Siberian Husky howls" << endl; } };
虚继承确保每个基类(Animal
)在派生类(SiberianHusky
)中只存在一个实例,从而避免菱形继承问题。
实战案例
#include <iostream> using namespace std; class Shape { public: virtual double area() const = 0; }; class Rectangle : public Shape { public: Rectangle(double width, double height) : m_width(width), m_height(height) {} double area() const override { return m_width * m_height; } private: double m_width; double m_height; }; class Circle : public Shape { public: Circle(double radius) : m_radius(radius) {} double area() const override { return M_PI * m_radius * m_radius; } private: double m_radius; }; int mAIn() { // 创建形状的父类指针 Shape* shape; // 创建矩形对象并将其分配给父类指针 shape = new Rectangle(5, 10); cout << "矩形面积:" << shape->area() << endl; // 创建圆形对象并将其分配给父类指针 shape = new Circle(3); cout << "圆形面积:" << shape->area() << endl; return 0; }
以上就是C++ 虚拟函数与虚继承:揭示多重继承中的复杂性的详细内容。