哪个是最佳实践?在c++文件或头文件中定义字符串
Which is the best practice? Defining strings in C++ files or header files?
我有一个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
限制了这些常量的使用,那么当前的配置看起来很好。
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- C 通过char读取文件字符串的文件char;崩溃
- 我不明白如何将 toupper 和 isalpha 与.txt文件字符串输入一起使用
- 在 CPP 文件中使用 make 文件字符串变量
- 编译 PyGAMMA Mac Lion:g++ 找不到标准的 C++ 头文件(字符串/iostream..)
- 如何在c++中使用文件字符串作为命令
- 使用 TinyXML 解析 XML 文件字符串
- 递归下降解析器帮助(不读取文本文件字符串)