C++ Resolving the diamond problem

喜欢而已 提交于 2019-12-02 04:56:04

问题


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.


回答1:


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

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.




回答2:


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() and C::getInt() are ambiguous when you call simply d.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 via class B and 2nd via class 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.



来源:https://stackoverflow.com/questions/6704332/c-resolving-the-diamond-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!