哪种是最佳做法?在C ++文件或头文件中定义字符串?

时间:2014-06-06 22:16:01

标签: c++

我有一个解析和写入XML文件的C ++程序。由于XML文件中使用的标记是重复的,我在CPP文件本身中声明了一个公共字符串列表作为标记。我应该单独为字符串创建一个单独的头文件,还是将它们放在实现文件本身中?这是最好的做法?

以下是我的CPP文件:

#include<iostream>
#include<string>

const std::string POS_ID = "position-id-map";
const std::string HEIGHT = "height";
const std::string WIDTH = "width";
const std::string RATIO = "ratio";
.
.
.
.
//20 more strings

int main(int argc, char ** argv) {
    //do XML reading and other stuff
    return 0;
}

在单独的头文件中声明它会带来什么好处,直接在实现文件中声明它?

2 个答案:

答案 0 :(得分:2)

解决方案No.1

  • 在标题中将其声明为extern,并在&#39; .cpp&#39;中定义它们。文件。
  • 不要在标题文件中将它们定义为static,因为您会破坏one definition rule

解决方案No.2

  • 将它们声明为辅助类的static常量成员变量。将class定义放在头文件中(例如XML_constants.hpp)。在.cpp文件中定义它们(例如,XML_constants.cpp):

  // XML_constants.hpp
  struct XML {
    static const std::string POS_ID;
    static const std::string HEIGHT;
    static const std::string WIDTH;
    static const std::string RATIO;
  };

  // XML_constants.cpp
  const std::string XML::POS_ID = "position-id-map";
  const std::string XML::HEIGHT = "height";
  const std::string XML::WIDTH  = "width";
  const std::string XML::RATIO  = "ratio";

解决方案No.3

  • 如果main.cpp中这些常量的使用受到限制,那么您当前的配置看起来不错。

答案 1 :(得分:2)

好吧,既然你问了一个关于头文件的问题,你的程序可能包含(或最终会包含)多个实现文件,其中几个(或全部)包含头文件。

如果是这样,在头文件中定义繁重的const对象并不是一个好主意。 C ++中的const对象默认具有内部链接,这将阻止任何&#34;多个定义&#34;错误,但同时将在包含该头文件的每个翻译单元中创建每个这样重的对象的独立副本。没有充分理由做这样的事情是一件相当浪费的事情。

更好的想法是在头文件中提供非定义声明

// Declarations
extern const std::string POS_ID;
extern const std::string HEIGHT;
extern const std::string WIDTH;
extern const std::string RATIO;

并将定义放在一个且只有一个实现文件

// Definitions
extern const std::string POS_ID = "position-id-map";
extern const std::string HEIGHT = "height";
extern const std::string WIDTH = "width";
extern const std::string RATIO = "ratio";

请注意,必须在此方法中明确指定关键字extern,以便在默认情况下覆盖&#34;静态&#34; const的财产。但是,如果标头声明在定义时可见,则可以从定义中省略extern

相关问题