删除虚拟类成员的代码重复 [英] Remove code duplication for virtual class members

查看:98
本文介绍了删除虚拟类成员的代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在陷入一个奇怪的问题。我写了一个非常简化的版本。

I have got myself into a strange issue now. Ill write a really simplified version of the same.

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实现基本的虚函数几乎一样。但是其他一些类(der3,der4)也有自己的实现。但是仍然需要从base继承。

如何重构代码以便以oop方式删除代码重复?



我尝试过:



我不希望函数有公共代码,然后从der1和der2调用它。除非我将所有受保护的变量作为参数发送给它,否则这是不可能的。不太喜欢这个方法。

所以,寻找一个OOP方法来处理这个问题,



Now the problem.... both der1 and der2 implements the virtual functions of base pretty much the same way. But some other classes (der3, der4) has their own implementations. But still need to inherit from base.
How do i refactor the code to remove the code duplication in an oop manner?

What I have tried:

I don't want a function to have the common code and then from the der1 and der2 to call it. That won't be possible unless I send all the protected variables of base to it as an argument. Didn't quite like the approach.
So, looking for a OOP approach to handle this problem,

推荐答案

从中获取第三个类处理常见实现的基础:

Derive a third class from Base which handles the "common" implementation:
class Intermediate: public Base
   {
   ...
   }

然后从中派生你的课程:

Then derive your classes from that:

class der1: public Intermediate
   { 
   ...
   };

class der2: public Intermediate
   {
   ...
   }


这篇关于删除虚拟类成员的代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆