C ++解决钻石问题 [英] C++ Resolving the diamond problem

查看:175
本文介绍了C ++解决钻石问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能仅仅通过使用第一个继承的声明来解决钻石问题?我的意思是,

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 {};


c $ c>首先列出,不能只是通过默认(当它不明确时)使用 B :: getInt() if D :: getInt()被调用?种类PATH环境变量在UNIX和其他操作系统中的工作原理;如果在PATH变量的不同位置存在两个具有相同名称的东西,那么默认情况下将使用第一个位置(除非另有限定)。

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.

推荐答案

这是一个非常错误的解决方案。请考虑在以下情况下会发生什么:

It's a very buggy solution. Think what will happen in the following case:

public class A {
    public int getInt() {return 5;}
    public float getFloat() {return 5.0;}
};

public class B {
    public int getInt() {return 6;}
    public float getFloat() {return 6.0;}
};

public class C {
    public int getInt() {return 7;}
    public float getFloat() {return 7.0;}
};

public class D: public A, public B, public C {}

假设有人希望 D :: getInt 返回5,而另一个开发人员希望 D :: getFloat 返回7.0 (因此,不同的功能解析为不同的祖先)。第二个开发人员将改变继承顺序,并且根据 getInt ,所有代码路径中的错误都会发生变化。

Suppose that one will want D::getInt to return 5 while another developer wants D::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 on getInt.

这篇关于C ++解决钻石问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆