cpp文件中名称空间内常量的定义 [英] Definition of constant within namespace in cpp file

查看:79
本文介绍了cpp文件中名称空间内常量的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VS 2010中,我已经达到了这种奇怪的效果(对我来说).任何人都可以给它一些启发.

I've approached this strange ( for me ) effect in VS 2010. Can anyone smart shed some light on it please.

//Header.h
#include <string>
namespace MySpace {
extern const std::string SOME_CONST_STRING;
}

//Implementation.cpp
#include "Header.h"
using namespace MySpace;
const std::string SOME_CONST_STRING = "CONST_STRING_VALUE";

这会导致链接器输出错误LNK2001:无法解析的外部符号const MySpace :: SOME_CONST_STRING.

This causes linker to output error LNK2001: unresolved external symbol const MySpace::SOME_CONST_STRING.

但是当我这样更改Implementation.cpp时:

However when I change Implementation.cpp like this:

//Implementation.cpp
#include "Header.h"
namespace MySpace {
const std::string SOME_CONST_STRING = "CONST_STRING_VALUE";    
}

代码建立正常.

是否更喜欢在cpp文件中定义名称空间而不是使用它呢?

Is it good example for prefering defining of namespace in cpp file rather than using it ?

推荐答案

名称空间的全部要点是,特定名称空间中的名称独立于该名称空间之外的名称.程序可能同时具有 MySpace :: SOME_CONST_STRING 全局 :: SOME_CONST_STRING ,这是两个完全不相关的符号.链接器使用一个定义来满足对另一个的引用是错误的.

The whole point of namespaces is that names in a particular namespace are independent of names outside that namespace. A program could have both a MySpace::SOME_CONST_STRING and a global ::SOME_CONST_STRING, and these are two completely unrelated symbols. It would be wrong for the linker to use a definition of one to satisfy a reference to the other.

定义变量时,必须在所需的名称空间中对其进行定义.

When you define a variable, you have to define it in the namespace where you want it to be.

这篇关于cpp文件中名称空间内常量的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆