C++: Declare a global class and access it from other classes?

前端 未结 2 832
一生所求
一生所求 2021-01-05 03:19

I have a class which should be declared globally from main() and accessed from other declared classes in the program, how do I do that?

class A{ 
    int i;          


        
相关标签:
2条回答
  • 2021-01-05 03:38

    In C++ declaring a global instance of a class is a no-no.

    You should instead use the singleton pattern, which gives you a single instance of your object accessible from the entire application.

    You can find a lot of literature on C++ singleton implementation, but wikipedia is a good place to start.

    Thread safe singleton pattern implementation has already been discussed on stackoverflow.

    0 讨论(0)
  • 2021-01-05 03:42

    You probably really do not want to do this, but if you must - in the file that contains main:

    #include "A.h"
    A a;
    
    int main() {
     ...
    }
    

    and then in the files that need to access the global:

    #include "A.h" 
    extern A a;
    

    You will need to put the declaration of A in the A.h header file in order for this to work.

    0 讨论(0)
提交回复
热议问题