我在 C++ 中有一个像这样的经典菱形问题
A
/ \
B C
\ /
D
我知道这通常可以通过让 B 和 C 虚拟继承 A 来解决。
但我的问题是类 A 和 B 来 self 无法编辑的第三方库,并且 B 从 A 继承未标记为虚拟。
有办法解决吗?
感谢您的帮助;-)
最佳答案
解决这个问题的一个简单方法是引入一个Adapter类(class)。这样,层次结构就变成了
A
/
B AdapterC
\ /
D
AdapterC 的代码看起来像
class AdapterC
{
public:
explicit AdapterC(C c) : c(std::move(c)) {}
operator C& () { return c; } //Maybe this should be explicit too...
/** Interface of C that you want to expose to D, e.g.
int doSomething(double d) { return c.doSomething(d); }
**/
private:
C c;
};
俗话说,“All problems in computer science can be solved by another level of indirection, except of course for the problem of too many indirections”。当然,编写和维护这个 Adapter 的工作量可能会很大。因此,我认为评论您的问题的人可能是对的,您应该重新审视您的设计。
关于c++ - 与第三方库的菱形继承(钻石问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39335708/