What if I declare a class variable as extern so that it can access some global variable declared in some other file? Does such a scenario come up anytime or is it just a hypothetical case?

Lets say I have a header file global.h

extern int myglobalint;

and I have a cpp file my.cpp

Here I declare a class A

class A{
    //use that variable here....is it possible
}
有帮助吗?

解决方案

Yes it comes up from time to time, particularly in messy code. :D

Perhaps a more C++-like style would be to keep these kinds of variables together in a class, eg in global.h:

class Global { // You can do this with 'struct' & omit 'public'
public:
    static int myglobalint;
};

And in global.cpp:

int Global::myglobalint = 0xbeef;

There's really no advantage doing it with an extern or class members - but unless it's some kind of global setting or flag, if you're resorting to storing state globally you probably need to put some thought into your design.

If you really do need global variables, for example, state or configuration that really has no other place to live, I would choose the class-static approach over a mess of extern's.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top