【问题标题】:Unexpected inaccessible base (first derived class)意外无法访问的基础(第一个派生类)
【发布时间】:2017-06-11 20:36:39
【问题描述】:

以下代码给出了错误:'B' is an inaccessible base of 'D'。

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

谁能告诉我一个解决方法?当然除了公开继承。

#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;
 }

谢谢!

【问题讨论】:

  • 感谢您的回答!您能否将其发布为答案,以便我可以检查此问题是否已解决?

标签: c++ class oop inheritance compiler-errors


【解决方案1】:

你的例子可以缩小到

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

在派生类和派生类的友元范围之外,禁止转换为私有基类。错误与构造函数无关(它将按预期工作)。

您可能还想查看some workarounds

【讨论】:

  • 那么 B *p= new(B*) D; 是如何解释的?
  • 这看起来像一个语法错误。 new(B*)operator new 调用分配B * 并返回B * *
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 2014-06-22
相关资源
最近更新 更多