The example here doesn't make sense, but this is basically how I wrote my program in Python, and I'm now rewriting it in C++. I'm still trying to grasp multiple inheritance in C++, and what I need to do here is access A::a_print from main through the instance of C. Below you'll see what I'm talking about. Is this possible?
#include <iostream>
using namespace std;
class A {
public:
void a_print(const char *str) { cout << str << endl; }
};
class B: virtual A {
public:
void b_print() { a_print("B"); }
};
class C: virtual A, public B {
public:
void c_print() { a_print("C"); }
};
int main() {
C c;
c.a_print("A"); // Doesn't work
c.b_print();
c.c_print();
}
Here's the compile error.
test.cpp: In function ‘int main()’:
test.cpp:6: error: ‘void A::a_print(const char*)’ is inaccessible
test.cpp:21: error: within thi开发者_运维技巧s context
test.cpp:21: error: ‘A’ is not an accessible base of ‘C’
Make either B or C inherit from A using "public virtual" instead of just "virtual". Otherwise it's assumed to be privately inherited and your main() won't see A's methods.
精彩评论