c++ difference between std::string name and std::string &name -


i have lib.h, lib.cpp , test.cpp. ask better? lib.h

class c {     std::string name; }*cc; 

lib.cpp

{     std::cout << "the name is:" << name << std:: endl; } 

test.cpp

main() {      c tst;     tst.name="diana"; } 

what should use? std::string name or std::string *name? how can work &name, how code change , 1 of these 2 methods best one?

first, hardly believe code compile while in main try access private data member name.

about &. hard define start. in short std::string &name called reference object of type std::string. reference somehow alias other object. main feature is, have initialize refence object while creating , can't reinitialize reference point object. more feature can read in c++ faq

edit can declare public, protected , private members of class in arbitrary ordering:

class myclass { //here goes private members when working class //and public when working structs  public: //here goes public members protected: //here goes protected private:  //here goes private public:  //here goes public again }; 

ordering of members declaration code policy question. example, google style guide recommends put public members before private.

about hiding function members (not necessary private). can't hide function member declaration, there several ways "hide" implementation, not sure it's definition of hiding talking about. can check pimpl idiom. requires understanding of pointers advice start them first.

small code sample working pointer string:

#include <iostream> #include <string>  class myclass { public:  std::string *pstr; };  int main() {  std::string str("test");  myclass myobj;   myobj.pstr = &str;  std::cout << myobj.pstr->c_str()  << std::endl; } 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -