gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:32 28 4
gpt4 key购买 nike

我在代码中看到了这两种方法。你能解释一下这两者有什么区别吗?正如我认为它与 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com