简体   繁体   English

如何组织输入全局变量?

[英]How do I organize input global variables?

In some spare time, I'm working on some physical simulation code so I a) have a framework to build off of in the future and b) keep myself fresh with C++. 在业余时间里,我正在研究一些物理仿真代码,因此我a)有一个将来可以建立的框架,b)使自己对C ++保持新鲜。 I have several values (speed of light, box size, number of particles, things like that) that very nearly every part of the program needs, but I'd really like to give the user the ability to specify these values in an input.cfg file (so things like #DEFINE + a constants.h file won't work). 我几乎有程序的每个部分都需要几个值(光速,盒子大小,粒子数量,类似的东西),但是我真的很想让用户能够在输入中指定这些值。 cfg文件(因此#DEFINE + constants.h文件将无法工作)。 I can certainly read these values in fine, but what's the conventional/best way to make them available across many different modules? 我当然可以很好地阅读这些值,但是使它们在许多不同模块中可用的常规/最佳方法是什么?

How about a singleton: 单身呢:

class Universe {
private:
     Universe();

public:
    static Universe& GetInstance();

    void Reload();

    double GetSpeedOfLight() const { return m_C; }
    ...

private:
    double m_C; //!< Speed of light
};

Universe& Universe::GetInstance() {
    static Universe instance;
    return instance;
}

Universe::Universe() {
    Reload();
}

void Universe::Reload() {
    // load your constants
}

Instead of a pile of otherwise unrelated global variables, why not make a struct or class to contain these and have a function that retrieves or updates the current state of the configuration? 为什么不构造一个structclass来包含这些变量或class ,并拥有一个检索或更新配置当前状态的函数,而不是一堆其他不相关的全局变量?

For example, as a struct you could implement serialization methods to read from or write to a .cfg -type file. 例如,作为一种struct您可以实现序列化方法以读取或写入.cfg类型的文件。

That can also implement a static method to return the active configuration, so a global method that references a local variable in the implementation. 这也可以实现静态方法以返回活动配置,因此可以使用全局方法在实现中引用局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM