c++ - 写 "::namespace::identifier"和 "namespace::identifier"有什么区别?

标签 c++ namespaces nested

我在代码中看到了这两种方法。你能解释一下这两者有什么区别吗?正如我认为它与 C++ 完成命名空间查找的方式有关,您能否也提供一些相关信息,或者提供一个好的文档的链接?谢谢。

最佳答案

示例:

#include <cstdio>

namespace x {
    const int i = 1;
}

namespace y {
    namespace x {
        const int i = 2;
    }

    void func()
    {
        std::printf("x::i = %d\n", x::i);
        std::printf("::x::i = %d\n", ::x::i);
    }
}

int main()
{
    y::func();
    return 0;
}

输出:

x::i = 2
::x::i = 1

Explanation:

  • When you refer to an identifier like x::i, the definition used is the "closest" x::i. Inside ::y::func, the definition ::y::x::i is closer than the definition ::x::i. By contrast, there is no such function ::y::std::printf so ::std::printf is used instead.

  • When you refer to an identifier like ::x::i, there is no possible ambiguity: it looks for a top-level namespace named x, then finds an i inside.

So using :: at the beginning allows you to spell the full name of a global something. This also allows you to distinguish between local and global variables.

Example 2:

#include <cstdio>
const int x = 5;
int main()
{
    const int x = 7;
    std::printf("x = %d\n", x);
    std::printf("::x = %d\n", ::x);
    return 0;
}

输出:

x = 7
::x = 5

关于c++ - 写 "::namespace::identifier"和 "namespace::identifier"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8283079/

相关文章:

c++ - 如何在 Visual Code Editor 中为 C++ 项目准备/配置开发环境?

oop - 在 TCL 中列出命名空间中任何类的所有实例

c++ - 隐藏模板化辅助函数 - 静态成员或未命名的命名空间

xml - XML 命名空间有什么用?

c++ - 用户提供的显式默认函数定义为已删除的情况

c++ - 正确管理内存——创建包含指针的双向链表

c++ - 构建第一个项目时出现 Qt 错误 [Windows]

具有嵌套类的 C++ 抽象类。派生类和嵌套类

java - 二维映射中的迭代器

java - 如何编写一个输出三角形数字的java程序?