为什么在下面的代码中编译器抱怨这PureAbstractBase
是一个模棱两可的基类MultiplyInheritedClass
?PureAbstractBase
我意识到我有两个inMultiplyInheritedClass
和 that的副本,FirstConreteClass
并且SecondConreteClass
应该虚拟派生,因为它们是菱形的中间行(这确实解决了下面代码的问题)。但是,即使我有两个接口副本,为什么其中的代码MultiplyInheritedClass
不只是覆盖两者并明确选择定义的接口类MultiplyInheritedClass
?
#include <iostream>
using namespace std;
class PureAbstractBase {
public:
virtual void interface() = 0;
};
// I know that changing the following line to:
// class FirstConcreteClass : public virtual PureAbstractBase {
// fixes the problem with this hierarchy
class FirstConcreteClass : public PureAbstractBase {
public:
virtual void interface() { implementation(); }
private:
void implementation() { cout << "This is object FirstConcreteClass\n"; }
};
// I know that changing the following line to:
// class SecondConcreteClass : public virtual PureAbstractBase {
// fixes the problem with this hierarchy
class SecondConcreteClass : public PureAbstractBase {
public:
virtual void interface() { implementation(); }
private:
void implementation() { cout << "This is object SecondConcreteClass\n"; }
};
class MultiplyInheritedClass : public FirstConcreteClass,
public SecondConcreteClass {
public:
virtual void interface() { implementation(); }
private:
void implementation() { cout << "This is object MultiplyInheritedClass\n"; }
};
此外,为什么我对以下层次结构没有问题?在这种情况下,ConcreteHandler 类没有 AbstractTaggingInterface 的三个副本吗?那么为什么它没有与上面的示例相同的问题呢?
#include <iostream>
using namespace std;
class AbstractTaggingInterface {
public:
virtual void taggingInterface() = 0;
};
class FirstAbstractHandler : public AbstractTaggingInterface {
public:
virtual void taggingInterface() { cout << "FirstAbstractHandler\n"; }
virtual void handleFirst() = 0;
};
class SecondAbstractHandler : public AbstractTaggingInterface {
public:
virtual void taggingInterface() { cout << "SecondAbstractHandler\n"; }
virtual void handleSecond() = 0;
};
class ThirdAbstractHandler : public AbstractTaggingInterface {
public:
virtual void taggingInterface() { cout << "ThridAbstractHandler\n"; }
virtual void handleThird() = 0;
};
class ConcreteHandler : public FirstAbstractHandler,
public SecondAbstractHandler,
public ThirdAbstractHandler {
public:
virtual void taggingInterface() = { cout << "ConcreteHandler\n"; }
virtual void handleFirst() {}
virtual void handleSecond() {}
virtual void handleThird() {}
};
我正试图将所有这些都包裹起来,因为我最近与一位同事进行了交谈,他声称如果您从没有任何数据成员的纯虚拟类(接口)继承,则不需要虚拟继承。我认为理解为什么前一个代码示例不起作用而后者确实会在我脑海中直截了当(并弄清楚他的评论到底是什么意思)。提前致谢。