哪个是最佳实践?在c++文件或头文件中定义字符串

Which is the best practice? Defining strings in C++ files or header files?

本文关键字:文件 字符串 定义 c++ 最佳      更新时间:2023-10-16

我有一个c++程序来解析和写入XML文件。由于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;
}

在单独的头文件中声明它比直接在实现文件中声明它有什么好处?

既然你在问一个关于头文件的问题,那么你的程序可能由(或最终将由)多个实现文件组成,其中几个(或全部)包括你的头文件。

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

一个更好的主意是在头文件 中提供非定义声明。
// 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必须在这种方法中明确指定,以覆盖const的"默认静态"属性。但是,如果头声明在定义点可见,则可以从定义中省略extern

方案一

  • 在头文件中声明为extern,并在'.cpp'文件中定义。
  • 不要在头文件中将它们定义为static,因为这会打破一个定义规则。

解决方案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";

解决方案3号

  • 如果main.cpp限制了这些常量的使用,那么当前的配置看起来很好。