我知道 static
const
class
成员只能在 header 中初始化。命名空间是否相同?例如,这样写是否有效:
namehuman.hpp
namespace namehuman
{
string const human("human");
}
main.cpp
#include "namehuman.hpp"
cout << namehuman::human << endl;
我想知道包括头文件在内的所有文件是否都有自己的 string
human 拷贝,或者 human 是否是一个真正的全局变量(没有多次复制)。为了避免每个包含文件复制,我必须使用 extern
吗?
最佳答案
常量具有内部链接。因此,任何包含带有常量定义的 header 的编译单元都将拥有自己的对象实例。
根据C++标准(3.5程序和链接)
3 A name having namespace scope (3.3.6) has internal linkage if it is the name of
...
— a non-volatile variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage; or
如果你想要一个带有外部链接的常量,你必须用说明符extern
声明它,并在编译单元中定义它。
关于c++ - 命名空间中的 const 全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33402177/