简体   繁体   English

在C ++中的虚拟基类的两种实现之间共享方法

[英]Sharing methods between two implementations of a virtual base class in C++

I have a virtual base class and two classes that implement the various methods. 我有一个虚拟基类和两个实现各种方法的类。 The two classes have the same functionality for one of the methods. 对于这两种方法之一,这两个类具有相同的功能。 Is there away I can share the implementation between the two classes to eliminate redundant code? 我可以在两个类之间共享实现以消除冗余代码吗? I tried making the first class a parent of the second class in addition to the virtual base class but got a bunch of errors. 除了虚拟基类,我尝试使第一类成为第二类的父类,但出现了很多错误。

EDIT - Thanks everyone for the replies. 编辑 -谢谢大家的答复。 One thing I should have mentioned is that I cannot modify the virtual base class so just adding the code to the base class will not work. 我应该提到的一件事是,我无法修改虚拟基类,因此仅将代码添加到基类将无法正常工作。

Say, A is the base class, and B and C are classes that inherit from the base class. 说, A是基类,而BC是从基类继承的类。 The method whose logic is shared between B and C is called SomeMethod . BC之间共享逻辑的方法称为SomeMethod One of the following should do the trick, regardless of your use case: 无论使用哪种情况,以下方法之一都可以解决问题:

  • Take the logic for B::SomeMethod and C::SomeMethod and copy-and-paste it into A::SomeMethod B::SomeMethodC::SomeMethod的逻辑复制并粘贴到A::SomeMethod
  • Create a class D that provides the shared version of SomeMethod and have B and C derive from D , which will derive from A 创建一个类D ,该类提供SomeMethod的共享版本,并从D派生BC ,后者从A派生
  • Create a class SomeMethodImpl that just provides the implementation you want, and then the implementation of B::SomeMethod and C::SomeMethod will just delegate the method call to a private instance of SomeMethodImpl::SomeMethod 创建一个只提供所需实现的类SomeMethodImpl ,然后B::SomeMethodC::SomeMethod将方法调用委托给SomeMethodImpl::SomeMethod的私有实例

If you want to keep your base class as pure virtual, create another class that inherits from this one and implements that one function, and then have your two other classes inherit from this one: 如果要将基类保留为纯虚类,请创建从该类继承的另一类并实现该功能,然后让您的其他两个类从该类继承:

class Base { public: virtual void TheFunction(); /* blah blah other virtual functions */ };
class OneFunctionImplemented : public Base { public: virtual void TheFunction() { DoSomething(); } };
class ChildClass1 : public OneFunctionImplemented { };
class ChildClass2 : public OneFunctionImplemented { };

Place the shared functionality in the base class. 将共享功能放在基类中。 Both of the other classes will be able to access it from there. 其他两个类都可以从那里访问它。

I believe by virtual base class you mean a base class having a pure virtual function (an abstract class) and not deriving virtually from a base class. 我相信虚拟基类是指具有纯虚函数( 抽象类)并且实际上不是从基类派生的基类。 If this is the case, you can put the common implementation in this base class so that it is available for all the derived classes. 在这种情况下,可以将通用实现放在此基类中,以便所有派生类都可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM