简体   繁体   中英

C++ Initialize Class based global variables

I am trying to define few global variables which should be available all functions but would like to initialize from main program. Can anyone help me with the syntax? Please note that still a bit beginner with c++ classes etc. As I need to run the same copy of this program multiple times and don't want to have a same shared class across multiple instances of this program - need to ensure I create a new class in the main body. Also wanted to mention - printvars - is a pre-built function for me and I don't have control over passing any pointer variables to it - just that I can only use global variables in that function.

class gvars
{
   public:
   int x=0;
   int y=0;
   gvars() {}
   ~gvars() {}
};

std::unique_ptr<gvars> *g=NULL;  // Must be a pointer to class

//I can't pass any parameters to this function
//Only have control over the body of the program to access global vars
void printvars()
{
   std::cout << (*g).x << " " << (*g).y << std::endl;
}

int main()
{

  if (g==NULL)
  {
     g=new gvars();  // This is critical  - create a new class here only
  }

  (*g).x=10;
  (*g).y=20;

  printvars();  // Expected output :  10   20

  delete g;

  return 0;
}

Code is good except only line. Try change

std::unique_ptr<gvars> *g=NULL;  // Must be a pointer to class

to

gvars*g=NULL;

Program will create/delete new instance of your class on each run for sure. Also printvars should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM