c++ - Why can (false?A():B()).test() compile only when A and B have a subclass relationship? -


originally use this:

(true?a:b).test() 

instead of

(true?a.test():b.test()) 

in order save typing time if function has same name, thought should valid, found:

#include <stdio.h> class a{ public:     char test(){         return 'a';     } };  class b{ public:     char test(){         return 'b';     } };  int main(){     printf("%c\n",(false?a():b()).test());     return 0; } 

cannot compile, if b subclass of a:

#include <stdio.h> class a{ public:     char test(){         return 'a';     } };  class b : public a{ public:     char test(){         return 'b';     } };  int main(){     printf("%c\n",(false?a():b()).test());     return 0; } 

it can compile, why?

the reason (test?a:b) expression , must have type. type common type of , b, , unrelated types have no type in common. common type of base , derived class base class.

note question contains assumption only case compiles there's common base type. in fact, compiles if there's unambiguous conversion 1 type other.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -