返回
多态继承:C++ 中面向对象编程的强大功能
后端
2023-11-29 23:16:57
引言
多态继承是 C++ 中面向对象编程 (OOP) 的一项强大技术,它允许派生类通过其基类指针或引用来访问其成员函数。这使得我们能够创建灵活且可扩展的代码,因为我们可以根据需要动态地交换对象。
虚函数
虚函数是使用 virtual
修饰的类成员函数。当基类中的函数被标记为虚函数时,派生类可以覆盖它,并提供自己的实现。当通过基类指针或引用调用虚函数时,将调用派生类的实现。
class Shape {
public:
virtual double area() const = 0; // 纯虚函数,必须在派生类中实现
};
class Rectangle : public Shape {
public:
Rectangle(double width, double height) : _width(width), _height(height) {}
double area() const override { return _width * _height; }
private:
double _width, _height;
};
class Circle : public Shape {
public:
Circle(double radius) : _radius(radius) {}
double area() const override { return M_PI * _radius * _radius; }
private:
double _radius;
};
int main() {
Shape* shapes[] = {new Rectangle(2, 3), new Circle(5)};
for (Shape* shape : shapes) {
std::cout << shape->area() << std::endl;
}
return 0;
}
虚继承
虚继承用于解决菱形继承中出现的歧义问题。菱形继承是指一个派生类从两个具有相同基类的派生类派生。如果不使用虚继承,派生类的对象将包含基类的两个副本,这会导致额外的内存开销和混乱。
使用虚继承,派生类只包含基类的单个副本。当通过虚基类指针或引用访问派生类对象时,将访问该单个副本。
class Animal {
public:
Animal() { std::cout << "Animal constructor called" << std::endl; }
virtual ~Animal() { std::cout << "Animal destructor called" << std::endl; }
};
class Cat : public virtual Animal {
public:
Cat() { std::cout << "Cat constructor called" << std::endl; }
~Cat() { std::cout << "Cat destructor called" << std::endl; }
};
class Dog : public virtual Animal {
public:
Dog() { std::cout << "Dog constructor called" << std::endl; }
~Dog() { std::cout << "Dog destructor called" << std::endl; }
};
class Pet : public Cat, public Dog {
public:
Pet() { std::cout << "Pet constructor called" << std::endl; }
~Pet() { std::cout << "Pet destructor called" << std::endl; }
};
int main() {
Pet pet; // 只调用一次 Animal 构造函数
return 0;
}
结论
多态继承是 C++ 中面向对象编程的基石,它允许我们创建灵活且可扩展的代码。通过虚函数和虚继承,我们可以实现代码重用、动态绑定和消除菱形继承中的歧义问题。理解和掌握多态继承对于在 C++ 中编写高质量的软件至关重要。