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
看了该问题的人还看了