我有一种“三角形继承”的问题,如果存在这样的事情。基本上,我有一个抽象基类中定义了一个接口,以及一个策略类定义实施一部分接口,就像这样:我可以使用其他父类的虚拟方法的实现吗
class System
{
public:
Interface() = default;
virtual ~Interface() {}
virtual void doSomething() = 0;
virtual bool somethingDone() const = 0;
virtual int trait1() const = 0;
virtual bool trait2() const = 0;
};
class SomethingImplementation
{
public:
SomethingImplementation() = default;
void doSomething() { (void)0; }
bool somethingDone() { return true; }
};
然后,我有不同的接口的几种实现案例。在某些情况下,我想用简单的实现,而在其他我想自定义他们
class SystemA : public System, public SomethingImplementation {/*...*/};
class SystemB : public System, public SomethingImplementation {/*...*/};
class SystemC : public System, { /* with a custom implementation ... */ };
我无法弄清楚什么是类系统A或系统B的细节可能是什么使实施工作
解决方案1
using语句,似乎不这样做在这种情况下,任何东西。
59:13: error: cannot declare variable 'a' to be of abstract type 'SystemA'
22:7: note: because the following virtual functions are pure within 'SystemA':
6:18: note: virtual void System::doSomething()
7:18: note: virtual bool System::somethingDone() const
60:13: error: cannot declare variable 'b' to be of abstract type 'SystemB'
31:7: note: because the following virtual functions are pure within 'SystemB':
6:18: note: virtual void System::doSomething()
7:18: note: virtual bool System::somethingDone() const
63:38: error: invalid new-expression of abstract class type 'SystemA'
解决方案2
添加一个额外的接口类。创建一个SomethingInterface
类,并从SomethingInterface
继承Interface
和SomethingImplementation
。这将问题转化为常见的“钻石继承”问题,但我仍然无法让编译器做我想做的事情。
什么是使用来自另一大类实施一个父类的虚方法的方法是什么?
尝试虚拟继承:'类SystemA:公共系统,公共虚拟SomethingImplementation','类系统:公共虚拟SomethingInterface'等。 –
相同的错误http://cpp.sh/7kroo –
虚拟继承与此无关。 SomethingInterface和System没有共同的祖先类。 –