c++ - 访问虚拟派生类的成员/方法

标签 c++ inheritance multiple-inheritance

这里的例子没有意义,但这基本上是我用 Python 编写程序的方式,现在我正在用 C++ 重写它。我仍在努力掌握 C++ 中的多重继承,在这里我需要做的是通过 C 的实例从 main 访问 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’

最佳答案

使用“public virtual”而不只是“virtual”使 B 或 C 从 A 继承。否则它会被假定为私有(private)继承并且您的 main() 将看不到 A 的方法。

关于c++ - 访问虚拟派生类的成员/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1549130/

相关文章:

c++ - 如何在不删除字符的情况下将 SQLCHAR[200] 类型转换为 std::string?

c++ - 使用带有 TTF_OPENFONT() 的 qrc 文件

c++ - 从 std::multimap<> 中删除项目后,我可以继续使用迭代器吗?

Ruby - 结构和命名参数继承

Java多重继承,无需源代码

具有虚拟方法的 C++ 对象大小

java - 如何从静态 Main 方法访问当前实际类

C++ 抽象类和创建派生类

java - java中如何通过接口(interface)实现多继承?

python - 如何调用右侧定义的类中存在的方法。 Python继承。多重继承。 Dimond场景python继承