2015-10-21 6 views
1

donc mon code est un peu comme cecomment appeler variable d'une classe imbriquée en C++

class foo1 
{ 
    public: 
     foo1() 
     { 
      a = "text"; 
     } 

     void getString() 
     { 
      return a; 
     } 
    private: 
     string a; 
}; 

class foo2 
{ 
    public: 
     foo2() 
     { 
      foo3 boo3; 
     } 
     class foo3 
     { 
      public: 
       foo3() 
       { 
        foo1 boo1; 
       } 
      private: 
       foo1 boo1; 
     }; 
    private: 
}; 

int main() 
{ 
    foo2 object; 
    cout << /* ??? */ ; 
} 

Tout d'abord, est-il un problème avec la structure de code dans les classes, deuxièmement, que dois-je mettre en l'endroit du commentaire pour afficher la chaîne a dans l'objet foo2 i initialisé dans int main()?

+1

Jetez un oeil à ceci: http: //fr.cppreference.com/w/cpp/language/nested_types – Bathsheba

+2

Pas une bonne idée d'appeler des variables 'boo1' –

Répondre

6

Il y a plusieurs problèmes avec le code, je vais les expliquer avec le code commente

class foo1 
{ 
    public: 
     //use initializer lists to avoid extra copying 
     foo1() : a("text") 
     { 
     } 

     //change return type from void to a const reference to string 
     const string & getString() 
     { 
      return a; 
     } 
    private: 
     string a; 
}; 

class foo2 
{ 
    public: 
     //use initializer lists to avoid extra copying 
     foo2() : boo3() 
     { 
     } 
     class foo3 
     { 
      public: 
       //use initializer lists to avoid extra copying 
       foo3() : boo1() 
       { 
       } 

       //you need a function that will allow access to the private member. Returning a const reference avoids extra copying 
       const foo1 & boo() 
       { 
        return boo1; 
       } 

      private: 
       foo1 boo1; 
     }; 

     //you need a function that will allow access to the private member 
     const foo3 & foo() 
     { 
      return boo3; 
     } 
    //you need to save the foo3 object in the class to be able to use it later 
    private: 
     foo3 boo3; 
}; 

int main() 
{ 
    foo2 object; 
    cout << object.foo().boo().getString(); 
} 

Maintenant, voici comment accéder à la chaîne:

cout << object.foo().boo().getString(); 
      \__________/ \___/ \_________/ 
       ^  ^  ^---- get the string from the foo1 object 
       |   |---- get the foo1 object from the foo3 object 
       |---- get the foo3 object stored in "object"