gcc keyword usage

I have two structures ("AAA" and "BBB") containing the same var name ("aa") and a third structure ("CCC"), defined using multiple inheritance. [the two structures must be disconnected, so this is not a famous problem with diamonds when the two classes have a common ancestor]. for the "CCC" derived structure, I tried to explicitly choose to work with var in the "AAA" derived structure, but gcc still complains about the ambiguous def. why?

struct AAA { int aa; }; struct BBB { int aa; }; struct CCC : public AAA , public BBB { using AAA::aa; }; int main() { CCC ccc; return ccc.aa; } 

gives:

 x.cpp: In function 'int main()': x.cpp:4:34: error: request for member 'aa' is ambiguous x.cpp:2:18: error: candidates are: int BBB::aa x.cpp:1:18: error: int AAA::aa 
+4
source share
3 answers

This fails because aa is already in this area. using AAA.aa will return it to the scope again.

you can apply this to a type and extract it that way.

 #include <iostream> struct AAA { int aa; AAA() : aa(1) {} virtual ~AAA(){}; }; struct BBB { int aa; BBB() : aa(5) {} virtual ~BBB(){}; }; struct CCC : public AAA , public BBB { CCC() : AAA(), BBB() {} // using AAA::aa; }; int main() { CCC ccc; std::cout << static_cast<BBB*>(&ccc)->aa << std::endl; } 

Although, if this is something that you intend to do a lot, it may be easier to just encapsulate this functionality.

 //member of CCC int get_aa() { return static_cast<BBB*>(this)->aa; } 
+5
source

You can set pointers to the corresponding members:

 struct AAA { int aa; }; struct BBB { int aa; }; struct CCC : public AAA , public BBB { int *A_aa; int *B_aa; CCC(): A_aa(&static_cast<AAA*>(this)->aa), B_aa(&static_cast<BBB*>(this)->aa) { } }; int main() { CCC ccc; return *ccc.A_aa; } 
0
source

You can use Virtual Inheritance . For example, this code should be rewritten as follows:

 struct AAA { int aa; }; struct BBB { int aa; }; struct CCC : virtual public AAA , virtual public BBB { using AAA::aa; }; 
0
source

Source: https://habr.com/ru/post/1399806/


All Articles