环境: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()...”作为输出。
1条答案
按热度按时间m1m5dgzv1#
试试这个
class Derived : public Base, public Base2
编辑:您提供的代码无法编译,这里有一个可以: