我问了这个问题:
Best Way to Refactor Class Hierarchy
以这种糟糕的方式,我在逻辑上被迫接受完全正确的答案。我的问题如下:
我有一个班级CGrandMother
,其公共方法virtual bool Compute()
可以
virtual bool Compute()
{
return false;
}
来自CGrandMother
的{{1}}公开CMother
未实现Compute
。现在CMother
公开C1
和C2
来实现virtual bool Compute()
。现在virtual bool C1::Compute()
和virtual bool C2::Compute()
分别为C1
和C2
做了很多适当的事情,但也有很多相同的内容适用于CMother
。现在有一个类CFamily
作为成员指向CMother
,并且代码Compute
中几乎所有地方都通过表单行调用
ptrCMother->Compute();
我想分析与CMother
和C1
中完成的C2
相关的常见内容,以便我不必更改所有ptrCMother->Compute();
。当然,我可以在CMother
中创建一个成员函数,并在bool C1::Compute()
和bool C2::Compute()
中调用后者。但...
在c++
中,B
来自A
,A::dostuff()
和B::dostuff()
以及p
是否指向某个类型{{ 1}}然后B
将通过多态实现p->dostuff()
。我想知道是否有一个成语/模式允许我实现这一目标:“B::dostuff()
”将执行“p->dostuff()
”或不执行(根据A::dostuff()
让我们说)然后“ bool
“,当然不会在B::dostuff()
中发生非构造函数的类成员函数等。
要明确:在通过间接调用相应的派生方法之前,不会调用基本方法。是否有一个习惯用法/模式允许在相应的派生方法之前调用make(或根据c++
)来生成基本方法?
答案 0 :(得分:0)
您提到的解决方案有什么问题,包括在CMother类中创建一个由其子级调用的方法?
#include <iostream>
#include <memory>
using namespace std;
class CGrandMother
{
private:
virtual bool _Compute()
{
return false;
}
public:
bool Compute()
{
return _Compute();
}
};
class CMother : public CGrandMother
{
protected:
void _CommonStuff()
{
cout << "work common to children" << endl;
}
};
class C1 : public CMother
{
private:
virtual bool _Compute() override
{
_CommonStuff();
cout << "work specific to C1" << endl;
return true;
}
};
class C2 : public CMother
{
private:
virtual bool _Compute() override
{
_CommonStuff();
cout << "work specific to C2" << endl;
return true;
}
};
int main() {
unique_ptr<CMother> c1(new C1);
unique_ptr<CMother> c2(new C2);
c1->Compute();
c2->Compute();
return 0;
}
请注意,我已经限制了我的课程的访问修饰符:
此外,您使CMother从CGrandMother公开继承,这意味着CMother 是CGrandMother。这是真的吗?
另请注意,如果CMother是层次结构的头部,那么您可以通过其公共(但非虚拟!)Compute方法调用_CommonStuff(),并且所有子类也会自动调用_CommonStuff()。这是关于这种模式的好处之一:你可以轻松地让你的Compute()方法完成所有子类共有的工作,检查不变量等等。
看起来像这样:https://ideone.com/vXd4fL
我删除了CGrandMother,CMother现在是我的层次结构的负责人。在其公共方法Compute()中,我调用_CommonStuff()。孩子们只需要实现_Compute()。所有孩子在调用Compute()时都会自动调用_CommonStuff()。