创建集中变量文件

时间:2014-08-29 19:10:33

标签: c++

我正在制作一个自组织地图程序。 对于它,我试图创建一种方法,我可以集中所有可以设置的用户/开发人员变量。我一直在尝试使用Config.h / .cpp文件但不确定这是否是正确/最佳方法。

似乎我没有以恰当的方式把事情放在编译错误的地方。

问题是集中在编译和运行之间必须改变的变量的最佳/正确方法吗?

的config.h

#ifndef CONFIG_H_
#define CONFIG_H_


class Config{

public:


    static const std::string outputFileLocation;// 
    static const std::string inputFilename;// 
    static const std::string outputFileExt;//

    unsigned int vectorLength = 3;//RGB


    //VARIBLE USED IN SOM CLASS
    static const int NODE_GRID_HEIGHT = 100;
    static const int NODE_GRID_WIDTH = 100;


};

#endif /* CONFIG_H_ */

Config.cpp

#include "Config.h"

//location to store output soms at it is iterated through
std::string Config::outputFileLocation = "/home/projectFiles/testMedia/results/mySom_";

//extension to put on output soms.
std::string Config::outputFileExt = ".jpeg";

////starting rgb image file to proccess
std::string Config::inputFilename = "/home/projectFiles/testMedia/yellowColor3.jpg";


////Length of muliti-dimensional data point. ie. a pixel.
unsigned int Config::vectorLength = 3;

2 个答案:

答案 0 :(得分:1)

这是将配置保持在不同类中的有效方法。因此,您将能够为默认配置定义构造函数,以及配置加载和保存方法。

但是在代码中存在轻微的一致性问题。

如果您声明:

   static const std::string outputFileLocation;  // you said const  

然后你应该把它定义为const:

   const std::string Config::outputFileLocation = "/home/projectFiles/testMedia/results/mySom_";

相反,如果您定义非静态数据成员:

   unsigned int vectorLength = 3;   //You already intialise it here 

你不应该像你那样重新定义它。这只是静力学所必需的。

但是,我想知道为什么要制作静态const。这要求它们被初始化(如果它们是静态的,或者作为普通成员的构造函数的一部分),它们可能不会随后更改。这可以防止您更改配置,例如在启动时加载配置文件。

其他想法

一旦有了配置类,就可以轻松地确定在编译时修复了哪个变量,哪些变量应该动态初始化。动态地可以是例如:

  • 读取配置文件(请参阅:此SO question)。

  • 通过系统环境获取一些变量(参见getenv()

  • 系统特定的方法,但是这不应该是便携式的,所以应该小心考虑(对于Windows,它通常是例如使用registry

  • 使用传递给main()的命令行参数。

答案 1 :(得分:0)

我推断您使用代码运行实验,因为您需要在编译和运行之间更改变量值。我过去做过这个的一个简单方法是将一个未命名的命名空间内的所有内容集中在头文件中。这样,您可以删除static声明,只需#include您需要的配置文件。

像这样。

<强> Configs.h

#ifndef CONFIG_H_
#define CONFIG_H_

namespace{

    const std::string outputFileLocation = "something";// 
    const std::string inputFilename = "something";// 
    const std::string outputFileExt = "something";//

    unsigned int vectorLength = 3;//RGB    

    //VARIBLE USED IN SOM CLASS
    const int NODE_GRID_HEIGHT = 100;
    const int NODE_GRID_WIDTH = 100;

};
#endif

请注意,这可能不是最佳解决方案,但简单有效。根据项目的目标,您可能需要考虑更优雅的解决方案。

另一个建议

假设我的推论是正确的,从配置文本文件中读取这些值也是一个不错的选择。您不需要在运行之间重新编译,如果您有一个大型项目,这可能非常耗时,并且许多其他文件依赖于该单个配置。