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

发布于 2024-08-07 03:22:42 字数 786 浏览 1 评论 0原文

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

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 this context
test.cpp:21: error: ‘A’ is not an accessible base of ‘C’

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

獨角戲 2024-08-14 03:22:42

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文