问题
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