【发布时间】:2019-03-25 14:40:03
【问题描述】:
我现在陷入了一个奇怪的问题。我会写一个非常简化的版本。
class Base
{
public:
virtual int func1()=0;
virtual int func2()=0;
protected:
int n;
};
class der1: public Base
{
// implements the virtual functions of the base and uses the protected data
// members of the base.
};
class der2: public Base
{
// implements the virtual functions of the base and uses the protected data
// members of the base.
}
现在问题....der1 和der2 都以几乎相同的方式实现 base 的虚函数。但是其他一些类(der3、der4)有自己的实现。但仍然需要从基础继承。
如何重构代码,以 oop 的方式去除重复代码?
【问题讨论】:
-
可以在基类中提供常用代码作为受保护的成员函数。
-
您可以从
Base12派生Der1和Der2,而Base12本身派生自Base。 -
正如我所说,只有两个类有共同的代码,而其他一些类有不同的公共代码集。因此,没有通用代码可以满足所有这 4 个类的需求。同样,将来可能会有更多的类继承这个基类。因此,真的不想打扰基类。
-
@lifeOfPi 那么@Evg 的提议可能是要走的路。
-
您也可以保留
Base12抽象,不需要实例化这些...无论如何,我更倾向于πάντα ῥεῖ 解决方案 - 如果有共同点,请定义它在Base中,然后在Der3和Der4中覆盖此实现。不需要再增加一层抽象。
标签: c++ inheritance refactoring protected code-duplication