C ++名称空间混乱-std :: vs :: vs tolower调用时没有前缀吗? [英] C++ name space confusion - std:: vs :: vs no prefix on a call to tolower?

查看:99
本文介绍了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是一个字符串.我是using namespace 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;指示编译器在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;,而应明确使用例如using 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调用时没有前缀吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆