【问题标题】:Accessing a member/method of a virtual derived class访问虚拟派生类的成员/方法
【发布时间】:2009-10-10 21:35:13
【问题描述】:

这里的例子没有意义,但这基本上是我用 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’

【问题讨论】:

    标签: c++ inheritance multiple-inheritance


    【解决方案1】:

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

    【讨论】:

    • 这是一个很好的观点:将两个继承路径之一公开以授予访问权限就足够了。所采用的路径是提供最多访问权限的路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多