It seems that I can only achieve my goal by casting the pointer ... The grammar of the egg ache
#include <iostream>#include<vector>#include<memory>using namespacestd;classA { Public: Virtual voidinit () =0;};classD | PublicA { Public: voidinit () {cout<<"B Init"<<Endl; }};classC: PublicB { Public: voidprint () {cout<<"C-B"<<Endl; } voidinit () {cout<<"C Init"<<Endl; }};classB | PublicA {Private: intWow; Public: D () {Wow=0; } D (inta): Wow (a) {}voidinit () {cout<<"D Init"<<Endl; } voidprint () {cout<<"D-A"<< Wow <<Endl; }};intmain () {vector<shared_ptr<A>>list; List.push_back (make_shared<C>()); List.push_back (make_shared<D> (1)); for(Auto &item:list) {Item-init (); } ((D*) list[1].Get())print (); return 0;}
This enables all objects to be placed in a container ... But when it's used ... Also remember the corresponding type, to be converted ...
Add a macro to help convert
#define Ptr_convert (shared_ptr, type) ((type*) shared_ptr.get ())
Ptr_convert (List[0], C)->print ();
Ptr_convert (list[1], D)->print ();
[Written by the blind JB] C + + polymorphic