How to declare a global variable that could be used in the entire program

后端 未结 9 1052
别那么骄傲
别那么骄傲 2020-12-13 14:52

I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I would like to use it. How would I accomplish th

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 15:43

    If you're not going to use the Singleton pattern as Lyndsey suggests, then at least use a global function (inside a namespace) to access the variable. This will give you more flexibily in how you manage that global entity.

    // mymodule.h
    namespace mynamespace // prevents polluting the global namespace
    {
       extern int getGlobalVariable();
    }
    
    // mymodule.cpp
    namespace mynamespace
    {
       int myGlobalVariable = 42;
    
       int getGlobalVariable()
       {
          return myGlobalVariable;
       }
    }
    

提交回复
热议问题