溫馨提示×

C++繼承機制支持多繼承嗎

c++
小樊
81
2024-11-08 23:37:24
欄目: 編程語言

是的,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類繼承了Base1Base2類。因此,Derived類的對象可以訪問這兩個基類的公共方法。

0