2015-12-07 117 views
0

伙计们,我在科技博客上遇到过这个问题,问题是什么问题才能解决在下面的代码中产生的编译器错误。我搜索了几个小时,无法得到答案。访问基类从派生类中受保护的嵌套类

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中所说的,但有一些困难。 (我希望有人也可以实现在一个想法),下面是我的代码:

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

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

我们可以用什么来取代“derived :: Nest”?派生的确看到了Nest的定义,但我不知道如何“说”它。也许以某种方式通过“this”指针。

+0

您可以在派生使用巢类中声明use_someclass。 –

回答

0

您可以在派生类中改变的可视性:

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

谢谢。昨天经过一番搜索之后,我也发现了这一点。“使用SomeClass :: Nest”的作品。我们有其他选择吗? “使用”会打破受保护的限定符。 –

相关问题