我有一个设计问题。如果可能的话,我想使用来自“姐妹”类的函数实现。
我有一些“历史性”代码,使用继承将行为添加到基类。
///////////////// Historic code ////////////////:
class IBase
{
int value;
virtual int method(){
return value;
};
}
class DerivedHist : IBase {
void otherMethod(){
return;
}
}
经过一些修改,我最终将IBase专门化为2个派生类(Derived1和Derived2),并将IBase类更改为抽象类。 问题是我想将DerivedHist类的行为添加到两个类中,但我看不出如何很好地做到这一点。
///////////////////// New code //////////////////////////:
//this time IBase is an abstract class
class IBase
{
int value;
virtual int method() = 0;
}
class DerivedHist : IBase {
void otherMethod(){
return;
}
//I'd like to use Derived1's or Derived2's implementation
virtual int method(){
//???
}
}
class Derived1 : IBase {
virtual int method(){
return 2*value;
}
}
class Derived2 : IBase {
virtual int method(){
return 3*value;
}
}
我不知道如何准确地将DerivedHist类放回原位...
我想出了一些主意:
编写与DerivedHist等效的2个类,它们继承自Derived1(例如Derived1Hist)和Derived2(例如Derived2Hist), 但这意味着拥有两个几乎具有相同代码的类。
IBase
/ \
Derived1 Derived2
/ \
Derived1Hist Derived2Hist
在DerivedHist构造函数中使用类似的内容:
DerivedHist(IBase* other) : IBase(*other){
...
}
并通过动态强制转换进行调用:
Derived1 derived1(...);
DerivedHist derivedHist(dynamic_cast<IBase*>(derived1));
这不会使用method()的正确实现吗?正如我们可以调用dynamic_cast(new Derived1(...))-> method()一样,我认为在复制构造函数中传递这样的内容也是可行的。 我找不到用这种东西编译代码的方法...
已将Derived [1,2]对象之一作为成员
class DerivedHist : IBase {
IBase* methodHolder;
DerivedHist(IBase* other) : methodHolder(other){
...
}
void otherMethod(){
return;
}
virtual int method(){
//here I'd have to copy the relevant data members to the other object
methodHolder->value = value;
//and then call the other method
return methodHolder->method();
}
}
这似乎是3中的最佳解决方案。
但是在这里,我看到的问题是我没有从DerivedHist及其methodHolder成员同步数据。
我可以跟踪所有更改并将其应用于methodHolder,但这似乎不是完美的解决方案。
总而言之,我有两个主要问题: