从派生类访问基类保护嵌套类

时间:2015-12-07 08:14:32

标签: c++ inheritance polymorphism protected

伙计们,我在科技博客上遇到过这个问题,问题是什么是解决下面代码中生成的编译器错误的正确解决方案。我搜索了几个小时,但无法得到答案。

class SomeClass
{
public:
     int data;
protected:
     class Nest
     {
        public:
           int nested;
     };
public:
     static Nest* createNest(){return new Nest;}
};

void use_someclass()
{
    SomeClass::Nest* nst = SomeClass::createNest();
    nst->nested = 5;
}

A.    Make function void use_someclass() a friend of class SomeClass.
B.    Make the function createNest() a non-static function of SomeClass.
C.    Declare the class Nest in public scope of class SomeClass.
D.    Make the object nst a reference object, and make the function 
      createNest() return a Nest&.
E.    Derive a class from SomeClass. Make the object nst a derived class
      pointer so that it can access SomeClass's protected declarations.

C当然是正确的和琐事。 我相信A也是对的,特别是E是做这种事情的经典方式。 我希望实现E中所说的,但有一些难以理解。 (我希望有人也可以在A中实现这个想法,下面是我的代码:

class derived:public SomeClass{};
void use_someclass()
{
   derived::Nest  *nst=SomeClass::createNest();
   nst->nested = 5;
}

在上面,我们的想法是我们可以从派生类访问Nest定义。 在函数use_someclass()中,在第一行中,右侧是静态函数,并返回类型Nest *,但在左侧,我不知道如何匹配右侧类型。 "衍生::巢"是错的。编译错误:无法访问受保护的成员。 Nest只是SomeClass中的一个定义,而不是成员。

我们可以用什么来代替"衍生的:: Nest"?派生当然看到了Nest的定义,但我不知道如何"说"它。也许以某种方式通过"这个"指针。

1 个答案:

答案 0 :(得分:0)

您可以更改派生类中的可见性:

class derived : public SomeClass {
  public:
    using SomeClass::Nest;
}