gpt4 book ai didi

c++ - 全局命名空间不在其他命名空间中检查

转载 作者:行者123 更新时间:2023-11-28 07:18:49 25 4
gpt4 key购买 nike

我试图在我的代码中使用命名空间,所以我有一个如下所示的头文件:

#include <string>

namespace AppNamespace
{
class A
{
std::string name;
};
}

当我尝试编译它时,它说“'string' 不是 AppNamespace::std 的成员”。如果我删除字符串前面的 std::,或者如果我写 ::std::string name,那么它会编译正常。

这当然是一个简化的例子,我有很多头文件,但并不是所有的头文件都显示这种行为。我不确定是什么原因导致的,我认为编译器也会始终尝试使用全局命名空间。

如果这很重要,我目前正在使用 Visual Studio 2012。

最佳答案

This is of course a simplified example, I have many header files and not all of them show this behavior. I am not sure what can cause this, I thought that the compiler would always try the global namespace as well.

在某些时候你必须有这样的东西:

namespace AppNamespace
{
#include <string> // or #include "my_header" which in turn includes <string>

class A
{
std::string name;
};
}

#include 指令不考虑 namespace 。您需要将它们全部移出到全局命名空间范围内,否则每个(可能嵌套的)标准 header 的包含将导致以创建嵌套命名空间 std 形式出现的未定义行为。

关于c++ - 全局命名空间不在其他命名空间中检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827840/

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