【问题标题】:access base class protected nested class from derived class从派生类访问基类受保护的嵌套类
【发布时间】:2016-03-11 18:56:03
【问题描述】:

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

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 中的一个定义,不是成员。

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

【问题讨论】:

  • 您可以在派生类中声明 use_someclass 以使用 Nest。

标签: c++ inheritance polymorphism protected


【解决方案1】:

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

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

【讨论】:

  • 谢谢。昨天经过一番搜索后,我也发现了这个。“使用 SomeClass::Nest”有效。我们还有其他选择吗? “使用”会破坏受保护的限定符。
猜你喜欢
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 2020-07-28
  • 2011-06-08
  • 2012-08-29
相关资源
最近更新 更多