C++解决钻石问题
仅仅使用找到的第一个继承声明就不能解决钻石问题吗?我的意思是,
public class A { public virtual int getInt(); }; public class B : public A { public int getInt() {return 6;} }; public class C : public A { public int getInt() {return 7;} }; public class D: public B, public C {};
对于 class D
来说,由于 B
列在最前面,我们难道不能在默认情况下(当它不明确时)使用 B::getInt()
如果 D::getInt()
被调用? PATH 环境变量在 UNIX 和其他操作系统中的工作原理;如果 PATH 变量中的不同位置存在两个同名的事物,则默认使用第一个位置(除非另有限定)。
编辑:通过发现“第一个”继承声明,我的意思是根据简单的从左到右深度优先顺序
编辑#2:刚刚更新了上面的实现,使其更加类似于钻石。
Couldn't the diamond problem be resolved just by using the first inherited declaration found? I mean,
public class A { public virtual int getInt(); }; public class B : public A { public int getInt() {return 6;} }; public class C : public A { public int getInt() {return 7;} }; public class D: public B, public C {};
for class D
, since B
is listed first, couldn't we just by default (when it's ambiguous) use B::getInt()
if D::getInt()
is called? Kind of how the PATH environment variable works in UNIX and other OS's; if two things exist with the same name in different locations in the PATH variable, then the first location shall be used by default (unless otherwise qualified).
Edit: by 'first' inherited declaration found I mean according to simple left-to-right depth-first order
Edit#2: Just updated the above implementation to be more diamond-like.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个非常有问题的解决方案。想想在以下情况下会发生什么:
假设一个开发人员希望 D::getInt 返回 5,而另一个开发人员希望 D::getFloat 返回 7.0(因此,不同的函数解析为不同的祖先)。第二个开发人员将更改继承顺序,并且错误将在所有依赖
getInt
的代码路径中蔓延。It's a very buggy solution. Think what will happen in the following case:
Suppose that one will want
D::getInt
to return 5 while another developer wantsD::getFloat
to return 7.0 (thus, different functions resolved to different ancestors). The second developer will change the order of inheritance and a bug will creep in all code paths depending ongetInt
.这不是钻石问题。 C++ 编译器的所有语法都是特定的,如果有任何歧义,它总是会抛出错误。
当您简单地调用<时,您的
A::getInt()
、B::getInt()
和C::getInt()
是不明确的代码>d.getInt()。编辑:
在您编辑的问题中,编译器仍然不会从继承中进行评估,因为某些程序员可能确实需要拥有
A
==> 的不同副本。第一个通过B 类
,第二个通过C 类
。请注意,所谓的钻石问题是人类特有的问题。对于 C++ 编译器来说,这只是又一种模式。在 C++ 哲学中,您不仅限于一种范例或模式。您可以选择多重继承。
This is not a diamond problem. C++ compiler is specific about all its syntax, if there is any ambiguity it will always throw error.
Here your
A::getInt()
,B::getInt()
andC::getInt()
are ambiguous when you call simplyd.getInt()
.Edit:
In your edited question, still compiler doesn't evaluate from the inheritance, because some programmers may really need to have different copies of
A
==> 1st viaclass B
and 2nd viaclass C
. Note that so called diamond problem is a problem characterized by humans. For C++ compiler, it's just one more pattern.In C++ philosophy, you are not restricted to only one paradigm or pattern. You can choose to have multiple inheritance of your choice.