“使用命名空间"是什么意思?确切地做? [英] What does "using namespace" do exactly?

查看:51
本文介绍了“使用命名空间"是什么意思?确切地做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下C ++测试代码未链接(gcc 4.9.2,binutils 2.25).错误是在函数"main"中:未定义对"X :: test"的引用.

The following C++ test code does not link (gcc 4.9.2, binutils 2.25). The error is In function 'main': undefined reference to 'X::test'.

01: #include <string>
02: #include <iostream>
03:
04: namespace X
05: {
06:     extern std::string test;
07: };
08:
09: using namespace X;
10: std::string test = "Test";
11:
12: int main()
13: {
14:    std::cout << X::test << std::endl;
15: }

由于第09行,我期望第10行定义在第06行声明的 X :: test 变量.我相信相反,声明了一个不相关的 test 变量并在全局名称空间中定义,因此出现链接错误.

Because of line 09, I was expecting line 10 to define the X::test variable declared on line 06. I believe that instead an unrelated test variable is declared and defined in the global namespace, hence the linking error.

问题:有人可以解释为什么我的期望不正确以及到底发生了什么吗?

Question: Could anyone please explain why my expectation was incorrect, and what is happening exactly?

不是答案:

  • 我可以将第10行更改为 std :: string X :: test ="Test"; .
  • 我不应该以使用命名空间"开头.

推荐答案

使用命名空间X的伪指令 使包含伪指令的命名空间内的命名空间 X 的名称可见.也就是说,在该范围内查找名称 n 时,可以找到 X :: n .但是,只有在编译器需要进行查找时,才会进行查找.

The directive using namespace X; makes names from namespace X visible inside the namespace containing the directive. That is, when looking up a name n in that scope, X::n can be found. However, it will only be looked for if the compiler needs to look for it.

在您的示例中,此声明:

In your example, this declaration:

std::string test = "Test";

在全局名称空间内的

保持原样是完全合理的.名称 test 与其他任何声明一样,被简单地引入.无需在任何地方查找.

inside the global namespace makes perfect sense as-is. The name test is simply introduced, as with any other declaration. No need to look it up anywhere.

这将是完全不同的鱼缸:

This would be an entirely different kettle of fish:

namespace X
{
  struct C
  {
    static std::string test;
  };
}

using namespace X;
std::string C::test = "Test";

在此代码中,编译器需要知道什么是 C 才能理解 C :: test 的定义.因此,它执行 C 的名称查找,由于使用了 using 指令,该名称确实找到了 X :: C .

In this code, the compiler needs to know what C is to make sense of the definition of C::test. It therefore does a name lookup of C, which indeed finds X::C thanks to the using directive.

这篇关于“使用命名空间"是什么意思?确切地做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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