访问虚拟派生类的成员/方法
这里的例子没有意义,但这基本上是我用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用“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.