In the last chapter , we have learned that a common basis pointer usage , but knowing the structure and class pointers in how to use it? Will introduce
If this chapter does not suit you, you can see the C ++ pointer directory
In the structure or class, a pointer to access its member functions or variables by " -> " operator or see Notes section of code, the operation of the comment section is not recommended :
#include <iostream> #include <cstring> using namespace std; struct STRUCT { string hello; }; int main() { STRUCT *str=new STRUCT; str->hello="Hello";//或者可以写成: (*str).hello="Hello" cout<<str->hello<<endl;//或者可以写成: cout<<(*str).hello<<endl; delete str; return 0; }
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 class CLASS 5 { 6 public: 7 string hello; 8 }; 9 int main() 10 { 11 CLASS *str=new CLASS; 12 str->hello="Hello";//同理 13 cout<<str->hello<<endl;//同理 14 delete str; 15 return 0; 16 }
NOTE: class of the public can not save, struct the public can save ( belonging to the grammar section, no explanation )
On the pointer type and operate like structure (either data type),
Note : be sure to give structure or class pointer declaration space, otherwise the output may be garbled or no output, I also recommend the use of smart pointers, so as not to apply to free up space
Recommended viewing: C ++ smart pointer
Other pointers content, it is recommended to see here