c++ 具有不同功能的多重继承

thtygnil  于 2023-03-25  发布在  其他
关注(0)|答案(1)|浏览(154)

环境:Windows 10,IDE:Code::Blocks 20.03我有一个关于C++中多重继承的基本问题。如果我有一个如下所示的代码:

class Base
{
public:
    Base() {}
    virtual ~Base() {}
    void show() {
        cout << "Base show()..." << endl;
    }
};

class Base2
{
public:
    Base2();
    virtual ~Base2();
    void show() {
        cout << "Base2 show()..." << endl;
    }
};
void f(Base *b) {
    b->show();
}
void g(Base2 *b2) {
    b2->show();
}

class Derived : public Base, Base2
{
public:
    Derived() {}
    virtual ~Derived() {}
    void show() {
        cout << "Derived show()..." << endl;
    }
};
void h(Derived *d) {
    d->show2();
}

//driver program
int main()
{
    Base b;
    Base2 b2;
    Derived d;

    f(&b);  //Base show()...
    g(&b2); //Base2 show()...
    h(&d);  //Derived show()...

    //passing derived object
    f(&d);  //Base show()... because of static binding
    g(&d);  //error: 'Base2' is an inaccessible base of 'Derived'

    return 0;
}

在编译过程中,编译器抛出'Base2' is an accessible base of 'Derived'错误。如果我想访问Base2的地址,以便它可以执行静态绑定函数,那么我需要做什么额外的事情?预期输出:根据编译时绑定“Base2 show()...”作为输出。

m1m5dgzv

m1m5dgzv1#

试试这个class Derived : public Base, public Base2
编辑:您提供的代码无法编译,这里有一个可以:

#include <iostream>

class Base
{
public:
    Base() {}
    virtual ~Base() {}
    void show() {
        std::cout << "Base show()..." << std::endl;
    }
};

class Base2
{
public:
    Base2() {}
    virtual ~Base2() {}
    void show() {
        std::cout << "Base2 show()..." << std::endl;
    }
};
void f(Base* b) {
    b->show();
}
void g(Base2* b2) {
    b2->show();
}

class Derived : public Base, public Base2
{
public:
    Derived() {}
    virtual ~Derived() {}
    void show() {
        std::cout << "Derived show()..." << std::endl;
    }
};
void h(Derived* d) {
    d->show();
}

//driver program
int main()
{
    Base b;
    Base2 b2;
    Derived d;

    f(&b);  //Base show()...
    g(&b2); //Base2 show()...
    h(&d);  //Derived show()...

    //passing derived object
    f(&d);  //Base show()... because of static binding
    g(&d);  //error: 'Base2' is an inaccessible base of 'Derived'

    return 0;
}

相关问题