从子类嵌套类访问基类方法

时间:2014-10-19 13:59:18

标签: c++ oop inner-classes nested-class

问题延伸this question

情况如下。我正在扩展内部类的虚方法:

class ClassOne {
public:
    class InnerClass {
    public:
            virtual void method1();
    protected:
        friend class ClassOne
    };    
protected:
    oftenUsedMethod();
private:
    friend class InnerClass;
};

void ClassOne::InnerClass::method1()
{
    #Do stuff with oftenUsedMethod();
}

class SubClassOne : public ClassOne {
    class DerivedInnerClass : InnerClass { 
        virtual void method1();
    };
};

void SubClassOne::DerivedInnerClass::method1()
{
    ##I need the access to the oftenUsedMethod???
}

这是一张试图澄清问题的图片:) enter image description here

InnerClass在其方法中使用ofthenUsedMethod(),并且可以访问它。为了能够扩展方法,我需要访问ofthenUsedMethod()中的DerivedInnerClass。这可以实现吗?

1 个答案:

答案 0 :(得分:1)

有两个问题需要克服:

  1. 默认情况下,内部类与外部类的实例没有关联,你必须通过给它指向外部类的指针来使这个依赖项显式化。如果你这样做,你需要注意内部阶级的实例不会超过他们所指的对象。
  2. 派生的内部类不是从外部类派生的,因此它无权访问其protected成员。您可以做的是将protected函数添加到调用该函数的InnerClass中。此函数是InnerClass的成员,派生类可以调用它。动态绑定将完成剩下的工作。
  3. 以上是C ++中的内容:

    #include <iostream>
    
    class ClassOne
    {
    
    protected:
    
      virtual void
      oftenUsedMethod()
      {
        std::clog << "ClassOne::oftenUsedMethod()" << std::endl;
      }
    
      class InnerClass
      {
    
      private:
    
        /** Pointer to an instance of the outer class. */
        ClassOne *const outer_;
    
      public:
    
        InnerClass(ClassOne *const outer) : outer_ {outer}
        {
        }
    
      protected:
    
        virtual void
        method1()
        {
          std::clog << "ClassOne::InnerClass::method1()" << std::endl;
          this->dispatch();
        }
    
        /**
         * Simply calls the protected member of the outer class.
         * Derived classes can therefore access it indirectly, too.
         *
         */
        void
        dispatch()
        {
          // Be aware: If *this->outer_ has already been destructed
          // (and there is no simple way for us to tell whether it has),
          // calling a member function on it will cause disaster.
          this->outer_->oftenUsedMethod();
        }
      };
    };
    
    class SubClassOne : public ClassOne
    {
    
    protected:
    
      virtual void
      oftenUsedMethod() override
      {
        std::clog << "SubClassOne::oftenUsedMethod()" << std::endl;
      }
    
      class DerivedInnerClass : public ClassOne::InnerClass
      {
    
        DerivedInnerClass(ClassOne *const outer) : InnerClass {outer}
        {
        }
    
      protected:
    
        virtual void
        method1() override
        {
          std::clog << "SubClassOne::DerivedInnerClass::method1()" << std::endl;
          this->dispatch();
        }
      };
    };
    

    override是一个C ++ 11功能,你不需要它,但它可以使你的意图清晰。