是的,C++支持多繼承
#include <iostream>
class Base1 {
public:
void methodBase1() {
std::cout << "Method from Base1" << std::endl;
}
};
class Base2 {
public:
void methodBase2() {
std::cout << "Method from Base2" << std::endl;
}
};
class Derived : public Base1, public Base2 {
public:
void methodDerived() {
std::cout << "Method from Derived" << std::endl;
}
};
int main() {
Derived d;
d.methodBase1(); // Calls methodBase1 from Base1
d.methodBase2(); // Calls methodBase2 from Base2
d.methodDerived(); // Calls methodDerived from Derived
return 0;
}
在這個例子中,Derived
類繼承了Base1
和Base2
類。因此,Derived
類的對象可以訪問這兩個基類的公共方法。