标签:style http color os io java strong ar for
http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem
The "diamond problem" (sometimes referred to as the "deadly diamond of death"[6]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and/or C has overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
For example, in the context of GUI software development, a classButtonmay inherit from both classesRectangle(for appearance) andClickable(for functionality/input handling), and classesRectangleandClickableboth inherit from theObjectclass. Now if theequalsmethod is called for aButtonobject and there is no such method in theButtonclass but there is an overriddenequalsmethod inRectangleorClickable(or both), which method should be eventually called?
It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. In this case, class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.
http://www.devx.com/tips/Tip/32035
While multiple inheritance is an extremely useful feature—escpecially in large scale software, it can also lead to a problem known as the DDD, or "Dreadful Diamond on Derivation," or simply "The Diamond Problem," shown in the following code:
class ElectricAppliance{ int voltage, public: int getVoltage ( ) const { return voltage; } } ; class Radio : public ElectricAppliance { / * ...* / } ; class Tape : public ElectricAppliance { / * ...* / } ; class RadioTape: public Radio, public Tape { / * ..* / } ; int main( ) { RadioTape rt ; int voltage = rt.getVoltage( ) ; /* Error - ambiguous call. Two copies getVoltage( ) exist in rt*/ }RadioTape is derived simultaneously from two base classes, each of which has its own copy of the methods and data members of ElectricAppliance. Consequently, the object rt has two ElectricAppliance subobjects. In cases like this, where you need to reduplicate data methods from a common base class, you should use virtual inheritance:
class Radio : virtual public ElectricAppliance { / * ..* / } ; class Tape : virtual public ElectricAppliance { / * ..* / } ; class RadioTape: public Radio, public Tape { / * ..* / }Now, class RadioTape contains a single shared instance of ElectricAppliance, so there are no ambiguities:
int voltage = rt .getVoltage( ) ; //OKNote: Because of the virtual keyword in the base-class portion of Radio and Tape, an instance of ElectricAppliance will have have only a single, base subobject. This eliminates the ambiguities.
The diamond problem is therefore avoided since there is always only one implementation of a specific method or property and no ambiguity arises.
标签:style http color os io java strong ar for
原文地址:http://my.oschina.net/jerikc/blog/308312