C++ : global structure

这一生的挚爱 提交于 2019-12-12 04:58:23

问题


In the same way than using global variable,

const double GRAVITY = 9.81;

int main(){}

I would like to use global structure

typedef struct {
    double gravity;
} WorldConfig;

WorldConfig WC;
WC.gravity = 9.81;

int main(){}

but this does not compile ("WC" does not name a type).

Is there a way to do this or alternatively, a good reason why using a global struct would be a super bad idea ?

thx


回答1:


Yes, initialize the global variable:

struct WorldConfig
{
    double gravity;
};

WorldConfig WC = { 9.82 };

int main() { }



回答2:


In C++ you don't need the typedef, this is not C. Also, you need to set the gravity member in the initializer:

struct WorldConfig {
    double gravity;
} WC = {9.81};

However, for such constants, you probably want them to be really constant, so you could do:

struct WorldConfig
{
    static constexpr double gravity = 9.81; // requires C++11
};



回答3:


Another solution is:

In your header:

struct WC
{
   static const double g;
};

In your source file:

const double WC::g = 9.81;

Please note that anonymous struc and typedef use is C-style, not C++.




回答4:


Even if you put it into the scope of a class or struct, if it's static it is still a global.

Putting it within a struct would be useful in a meta-programming world, i.e.

struct Earth
{
   static const double gravity;
};

struct Mars
{
   static const double gravity;
};

// pseudo code
template< typename PLANET >
someFuncOrClass
{
     using PLANET::gravity;
}

This gets resolved at compile time (compared to making Planet a class that has a gravity attribute).

The obvious alternative scoping option though is a namespace.

namespace WC
{
     static double gravity;
}


来源:https://stackoverflow.com/questions/16054254/c-global-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!