问题延伸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???
}
这是一张试图澄清问题的图片:)
InnerClass
在其方法中使用ofthenUsedMethod()
,并且可以访问它。为了能够扩展方法,我需要访问ofthenUsedMethod()
中的DerivedInnerClass
。这可以实现吗?
答案 0 :(得分:1)
有两个问题需要克服:
protected
成员。您可以做的是将protected
函数添加到调用该函数的InnerClass
中。此函数是InnerClass
的成员,派生类可以调用它。动态绑定将完成剩下的工作。以上是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功能,你不需要它,但它可以使你的意图清晰。