开发者

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

开发者 https://www.devze.com 2022-12-29 13:04 出处:网络
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?

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; 
  开发者_Python百科  int value(){ return i;}
};

class B{ 
   global A a; //or extern?? 
   int calc(){
       return a.value()+10;
   }
}

main(){
   global A a;
   B b;
   cout<<b.calc();
}


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消