C++ 虚继承:解决菱形继承问题 - 示例讲解
虚继承是 C++ 中的一种特殊的继承方式,用于解决多重继承中的菱形继承问题(Diamond Inheritance Problem)。在菱形继承中,派生类从两个或多个基类中继承相同的基类,而这些基类又继承自同一个共同的基类。为了避免出现重复的基类实例,我们可以使用虚继承。
下面是一个简单的虚继承的例子:
#include <iostream>
// 基类 Animal
class Animal {
public:
int age;
Animal(int _age) : age(_age) {}
void eat() {
std::cout << 'Animal eats.' << std::endl;
}
};
// 虚继承的中间类
class Mammal : virtual public Animal {
public:
Mammal(int _age) : Animal(_age) {}
void run() {
std::cout << 'Mammal runs.' << std::endl;
}
};
// 虚继承的中间类
class Bird : virtual public Animal {
public:
Bird(int _age) : Animal(_age) {}
void fly() {
std::cout << 'Bird flies.' << std::endl;
}
};
// 派生类
class Platypus : public Mammal, public Bird {
public:
Platypus(int _age) : Mammal(_age), Bird(_age), Animal(_age) {}
};
int main() {
Platypus p(5);
// 调用派生类的成员函数
p.eat();
p.run();
p.fly();
// 访问派生类继承的基类成员
std::cout << 'Platypus age: ' << p.age << std::endl;
return 0;
}
在上述示例中,我们有一个基类 Animal,以及两个虚继承的中间类 Mammal 和 Bird,它们都虚继承自 Animal。最后,我们有一个派生类 Platypus,它同时继承了 Mammal 和 Bird。
通过使用虚继承,我们可以避免 Platypus 类中出现两个 Animal 对象的问题。这样,当我们创建 Platypus 对象时,只会有一个 Animal 对象被实例化。同时,由于虚继承,Platypus 对象可以直接访问基类 Animal 的成员变量和成员函数。
在 main() 函数中,我们创建了一个 Platypus 对象,并演示了如何调用派生类和基类的成员函数,以及访问基类的成员变量。
这个例子展示了虚继承的用法和好处,特别是在多重继承中避免冗余的基类对象。
原文地址: https://www.cveoy.top/t/topic/VZG 著作权归作者所有。请勿转载和采集!