意外的无法访问的基(第一个派生类) [英] Unexpected inaccessible base (first derived class)

查看:55
本文介绍了意外的无法访问的基(第一个派生类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码给出了错误: B是 D的不可访问基数。

The following code gives the error: 'B' is an inaccessible base of 'D'.

为什么会这样? B的构造函数是公共的,这意味着即使继承是受保护的/私有的,它也应由D类继承。

Why does this happen? The constructor of B is public which means it should be inherited by class D even though the inheritance is protected / private.

有人还能告诉我一种解决方法吗?

Can someone tell me a workaround as well? Except of course making the inheritance public.

#include <iostream>
#include <typeinfo>
using namespace std;
class B
{ int i;
   public: 
   B() { i=1; }
  int get_i() { return i; }
};
class D: private B  
{ int j;
  public:
   D() { j=2; }
  int get_j() {return j; }
 };
 int main()
 { 
 B *p= new D; 
 return 0;
 }

谢谢!

推荐答案

您的示例可以缩小为

D * p_d{nullptr};
B * p_b{p_d};

禁止在派生类和派生类的朋友范围之外进行私有基类的铸造。错误与构造函数无关(它将按预期工作)。

Casting to private base class is prohibited outside of derived class and derived class's friends scope. Error has nothing to do with constructor (which will work as expected).

您可能还需要检查

You may also want to check some workarounds.

这篇关于意外的无法访问的基(第一个派生类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆