gpt4 book ai didi

c++ - 为什么在命名空间前加上::,例如::std::vector

转载 作者:可可西里 更新时间:2023-11-01 15:36:10 26 4
gpt4 key购买 nike

我看过生产代码如

::std::vector<myclass> myvec;

我不知道前面的 :: 是什么意思 - 为什么要使用它?

例子见:

C++: Proper way to iterate over STL containers

最佳答案

这完全限定了名称,因此仅使用全局命名空间中 std 命名空间中的 vector 模板。它基本上意味着:

{global namespace}::std::vector<myclass> myvec;

当您在不同的命名空间中具有相同名称的实体时,可能会有所不同。有关何时这可能很重要的简单示例,请考虑:

#include <vector>

namespace ns
{
namespace std
{
template <typename T> class vector { };
}

void f()
{
std::vector<int> v1; // refers to our vector defined above
::std::vector<int> v2; // refers to the vector in the Standard Library
}
};

由于不允许在 std 命名空间中定义自己的实体,因此可以保证 ::std::vector 将始终引用标准库容器。 std::vector 可能指的是其他东西。 .

关于c++ - 为什么在命名空间前加上::,例如::std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4925394/

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