问题
Consider this (completely non-nonsensical, but perfectly valid) class inheritance:
struct Area { int size; };
struct Pattern { int size; };
struct R : Area, Pattern {};
struct C : Area, Pattern {};
struct X: R , C {};
Let's see a graph of this great hierarchy:
Area Pattern
|\ /|
| \/ |
| /\ |
|/ \|
R C
\ /
\/
X
Now, if I am not mistaken, X should have 4 size
members.
How to refer to them using the scope operator?
The obvious solution doesn't work:
X x;
x.R::Area::size = 24;
clang error:
23 : <source>:23:3: error: ambiguous conversion from derived class 'X' to base class 'Area': struct X -> struct R -> struct Area struct X -> struct C -> struct Area x.R::Area::size = 8; ^ 1 error generated.
gcc error:
<source>: In function 'auto test()': 23 : <source>:23:14: error: 'Area' is an ambiguous base of 'X' x.R::Area::size = 8; ^~~~
Some much needed clarification:
I was just messing around, it is not a real design
- so please don't point the problems with the design
- and please don't think this is a good design. It is... not - to say the least
This is strictly about the C++ syntax to resolve the ambiguity.
- please don't suggest to not do it
- please don't suggest virtual inheritance.
回答1:
something like static_cast<R&>(x).Area::size = 8;
which is as ugly as it should be :)
To clarify why the original code doesn't work, it's worth mentioning that a qualified id has the form (among others) type-name::id
so x.R::Area::y
is equivalent to using T = R::Area; x.T::y;
that clearly does not help as far as disambiguation is concerned.
来源:https://stackoverflow.com/questions/46648905/scope-operator-for-base-class-in-super-multiple-non-virtual-inheritance