Extending a nested class method

岁酱吖の 提交于 2019-12-24 12:33:45

问题


I have encountered a virtual method in a nested class.

##classone.h

class ClassOne: {
public:
  class InnerClass{
  public:
      virtual void method1();
      ...

##classone.cpp
void ClassOne::InnerClass::method1()
{
...
}

I am subclassing ClassOne and need to extend method1(). What need's to be done with the nested class in that situation?

What I tried

##subclassone.h

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

##subclassone.cpp

void SubClassOne::InnerClass::method1()
{
##New implementation
}

But that gives a multiple definition of ClassOne::InnerClass::method1()


回答1:


method1 belongs to ClassOne::InnerClass, not ClassOne. When you inherit from ClassOne, the nested class from base class becomes a member of the derived class, too, and you can reach it by qualifying with either ClassOne:: or SubClassOne::. Hence the double definition error regarding method1.

You'll need to sub-class InnerClass, too. If you still wish to derive from ClassOne, it would look like this:

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

void ClassOne::InnerClass::method1()
{
}

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

void SubClassOne::DerivedInnerClass::method1()
{
}


来源:https://stackoverflow.com/questions/26450244/extending-a-nested-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!