开发者

Accessing a member/method of a virtual derived class

开发者 https://www.devze.com 2022-12-08 18:55 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消