问题
We know that we can solve the diamond problem using virtual inheritance.
For example:
class Animal // base class
{
int weight;
public:
int getWeight() { return weight;};
};
class Tiger : public Animal { /* ... */ };
class Lion : public Animal { /* ... */ };
class Liger : public Tiger, public Lion { /* ... */ };
int main()
{
Liger lg ;
/*COMPILE ERROR, the code below will not get past
any C++ compiler */
int weight = lg.getWeight();
}
When we compile this code we will get an ambiguity error. Now my question is how compiler internally detects this ambiguity problem (diamond problem).
回答1:
The compiler builds tables that list all the members of every class, and also has links that allow it to go up and down the inheritance chain for any class.
When it needs to locate a member variable (weight in your example) the compiler starts from the actual class, in your case Liger. It won't find a weight member there, so it then moves one level up to the parent class(es). In this case there are two, so it scans both Tiger and Lion for a member of name weight. There aren't still any hits, so now it needs to go up one more level, but it needs to do it twice, once for each class at this level. This continues until the required member is found at some level of the inheritance tree. If at any given level it finds only one member considering all the multiple inheritance branches everything is good, if it finds two or more members with the required name then it cannot decide which one to pick so it errors.
回答2:
When compiler creates a table of function pointers for a class, every symbol must appear in it exactly once. In this example, getWeight
appears twice: in Tiger
and in Lion
(because Liger
doesn't implement it, so it goes up the tree to look for it), thus the compiler gets stuck.
It's pretty simple, actually.
回答3:
The compiler looks for getWeight in Liger, finds none, then check its parents and its parent's parents and so on and so forth, if it finds more than one, it returns an error and dies on you, because it can not tell which one it should use.
回答4:
With your code, the structure for liger is
Liger[Tiger[Animal]Lion[Animal]]
If you call an Animal
function from a Liger
pointer, there are actually two Animal a Liger can convert to (hence the ambiguity)
Virtual inheritance will generate a structure like
Liger[Tiger[*]Lion[Animal]]
\-----/
There is now just one Animal, indirectly reachable from both of the bases, so a conversion from Liger to Animal is anymore ambiguous.
来源:https://stackoverflow.com/questions/7383840/how-does-the-compiler-internally-solve-the-diamond-problem-in-c