C++ name space confusion - std:: vs :: vs no prefix on a call to tolower?(C++ 名称空间混淆 - std:: vs :: vs 调用 tolower 时没有前缀?)
问题描述
这是为什么?
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.
这篇关于C++ 名称空间混淆 - std:: vs :: vs 调用 tolower 时没有前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 名称空间混淆 - std:: vs :: vs 调用 tolower 时没有前缀?
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
