C++ Initialize Class based global variables -
i trying define few global variables should available functions initialize main program. can me syntax? please note still bit beginner c++ classes etc. need run same copy of program multiple times , don't want have same shared class across multiple instances of program - need ensure create new class in main body. wanted mention - printvars - pre-built function me , don't have control on passing pointer variables - can use global variables in function.
class gvars { public: int x=0; int y=0; gvars() {} ~gvars() {} }; std::unique_ptr<gvars> *g=null; // must pointer class //i can't pass parameters function //only have control on body of program access global vars void printvars() { std::cout << (*g).x << " " << (*g).y << std::endl; } int main() { if (g==null) { g=new gvars(); // critical - create new class here } (*g).x=10; (*g).y=20; printvars(); // expected output : 10 20 delete g; return 0; }
code except line. try change
std::unique_ptr<gvars> *g=null; // must pointer class
to
gvars*g=null;
program create/delete new instance of class on each run sure. printvars
should work fine.
Comments
Post a Comment