C++ structure and class pointer points summary

  • 2020-06-19 11:19:54
  • OfStack

In a struct or class, a pointer accesses its member function or variable through "- > "Operator or look at the comment section of the code. Comment section operations are not recommended:


#include <iostream>
#include <cstring>
using namespace std;
struct STRUCT
{
  string hello;
};
int main()
{
  STRUCT *str=new STRUCT;
  str->hello="Hello";// Or we could write it as : (*str).hello="Hello"
  cout<<str->hello<<endl;// Or we could write it as : cout<<(*str).hello<<endl;
  delete str;
  return 0;
}

#include <iostream>
#include <cstring>
using namespace std;
class CLASS
{
public:
  string hello;
};
int main()
{
  CLASS *str=new CLASS;
  str->hello="Hello";// In the same way 
  cout<<str->hello<<endl;// In the same way 
  delete str;
  return 0;
}

Note: public in class cannot be saved, while public in struct can be saved (it belongs to the grammatical part, without explanation).

Pointers to classes and structures operate like this (regardless of the data type),

Note: 1 must declare space for structure or class pointer, otherwise the output may be gibber or no output, I recommend using smart pointer to avoid applying for free space

This is the introduction of C++ structure and class pointer all the knowledge content, thank you for your reading and support for this site.


Related articles: