问题描述
假设我们有一个带有公共接口的基类 Base
,以及一些用于支持公共接口的受保护方法。简化示例:
class Base {
protected:
virtual int helper() const = 0;
public:
virtual void do_work() {
//By default,just call the helper. Descendants can customize behavIoUr.
int x = helper();
do_something_with_an_int(x);
}
};
假设我们有一些后代 DerivedA
,DerivedB
,DerivedC
...实现了这个接口。
我想将工作分成两个函数(而不是仅仅使用 do_work
来做所有事情)的原因是因为我想要一个特殊的后代,它可能看起来像这样:
class DescendantWrapper : Base {
Base *impl;
int x;
protected:
int helper() const override {
x += impl->helper();
}
public:
void do_work() override {
helper();
if(some_internal_condition()) {
do_some_other_thing_with_an_int(x);
} else {
x = 0;
}
}
};
目的是允许 DescendantWrapper
包装 Base
的任何后代,并在其他代码中代替该后代。当然,其他代码不会知道它的 Base
的后代已经被包装了。
问题是派生类(在本例中为 DescendantWrapper
)无法在其父类的实例上调用受保护的方法(在本例中为 Base::helper()
).
一种解决方案是专门将 DescendantWrapper
声明为 Base
的朋友。但是,这意味着此代码的其他用户无法创建他们自己的后代包装器。有谁知道这种情况下友元函数的替代方法?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)