二级子类中不可访问的基

  • 本文关键字:访问 子类 二级 c++
  • 更新时间 :
  • 英文 :


为什么我不能成为Grand类型的类成员?

class Grand
{};
class Father :private Grand
{};
class Son :public Father
{
    Grand g; //This gives error. Class Grand is Inaccessible.
};

因为它自动在函数之前添加父类"spacename",并且Father::Grand::Grand()(构造函数)是私有

class Grand
{};
class Father :private Grand
{};
class Son :public Father
{
    ::Grand g; 
};

之所以有效,是因为直接使用Grand类,而不是继承

这修复了它:

class Grand
{};
class Father :private Grand
{};
typedef Grand MyGrand;
class Son :public Father
{
    MyGrand g; // This now compiles successfully
};

问题是,像private这样的说明符会影响名称查找中的可访问性,但不会影响可见性。因此,当您说Grand g时,编译器首先遍历继承树,以防您最终解决类似Grand::MyType的问题。

这是因为您的Grand被继承privateFather隐藏了,请尝试使用全局作用域:

class Son : public Father {
    ::Grand g;
};

最新更新