5

这里的例子没有意义,但这基本上是我用 Python 编写程序的方式,我现在用 C++ 重写它。我仍在尝试掌握 C++ 中的多重继承,我需要做的是从 main 通过 C 的实例访问 A::a_print。下面你会看到我在说什么。这可能吗?

#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();
}

这是编译错误。

test.cpp: In function ‘int main()’:
test.cpp:6: error: ‘void A::a_print(const char*)’ is inaccessible
test.cpp:21: error: within this context
test.cpp:21: error: ‘A’ is not an accessible base of ‘C’
4

1 回答 1

12

使用“公共虚拟”而不是“虚拟”使 B 或 C 从 A 继承。否则它被认为是私有继承的,你的 main() 不会看到 A 的方法。

于 2009-10-10T21:39:24.020 回答