C++ 名称空间混淆 - std:: vs :: vs 调用 tolower 时没有前缀?

2022-01-14 00:00:00 namespaces c++ name-decoration

这是为什么?

transform(theWord.begin(), theWord.end(), theWord.begin(), std::tolower); - 不起作用transform(theWord.begin(), theWord.end(), theWord.begin(), tolower); - 不起作用

transform(theWord.begin(), theWord.end(), theWord.begin(), std::tolower); - does not work transform(theWord.begin(), theWord.end(), theWord.begin(), tolower); - does not work

但是

transform(theWord.begin(), theWord.end(), theWord.begin(), ::tolower); - 确实有效

theWord 是一个字符串.我在 使用命名空间 std;

theWord is a string. I am using namespace std;

为什么它可以使用前缀 :: 而不是 std:: 或什么都没有?

Why does it work with the prefix :: and not the with the std:: or with nothing?

感谢您的帮助.

推荐答案

using namespace std; 指示编译器搜索未修饰的名称(即没有 :: 的名称s) 在 std 以及根命名空间中.现在,您正在查看的 tolower 是C 库,因此在根命名空间中,它始终位于搜索路径上,但也可以使用 ::tolower 显式引用.

using namespace std; instructs the compiler to search for undecorated names (ie, ones without ::s) in std as well as the root namespace. Now, the tolower you're looking at is part of the C library, and thus in the root namespace, which is always on the search path, but can also be explicitly referenced with ::tolower.

还有一个 std::tolower 然而,它需要两个参数.当你有 using namespace std; 并尝试使用 tolower 时,编译器不知道你的意思是哪个,所以它变成了一个错误.

There's also a std::tolower however, which takes two parameters. When you have using namespace std; and attempt to use tolower, the compiler doesn't know which one you mean, and so it' becomes an error.

因此,您需要使用 ::tolower 来指定您想要根命名空间中的那个.

As such, you need to use ::tolower to specify you want the one in the root namespace.

顺便说一句,这就是为什么 using namespace std; 可能是个坏主意的一个例子.std 中有足够多的随机内容(C++0x 添加了更多内容!)很可能会发生名称冲突.我建议您不要使用 using namespace std;,而是明确使用,例如具体使用 std::transform;.

This, incidentally, is an example why using namespace std; can be a bad idea. There's enough random stuff in std (and C++0x adds more!) that it's quite likely that name collisions can occur. I would recommend you not use using namespace std;, and rather explicitly use, e.g. using std::transform; specifically.

相关文章