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(), ::tolower);
- 确实有效
theWord 是一个字符串。我正在使用命名空间 std;
为什么它可以与前缀 ::
一起使用,而不是与 std::
一起使用或什么都不使用?
Why is this?
transform(theWord.begin(), theWord.end(), theWord.begin(), std::tolower);
- does not worktransform(theWord.begin(), theWord.end(), theWord.begin(), tolower);
- does not work
but
transform(theWord.begin(), theWord.end(), theWord.begin(), ::tolower);
- does work
theWord is a string. I am using namespace std;
Why does it work with the prefix ::
and not the with the std::
or with nothing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
using namespace std;
指示编译器在std
以及根命名空间中搜索未修饰的名称(即没有::
s 的名称) 。现在,您正在查看的tolower
是C 库,因此位于根命名空间中,该命名空间始终位于搜索路径上,但也可以使用::tolower
显式引用。还有一个
std::tolower
但是,它需要两个参数。当您使用using namespace std;
并尝试使用tolower
时,编译器不知道您指的是哪一个,因此它会成为错误。因此,您需要使用
::tolower
来指定您想要根命名空间中的那个。顺便说一句,这就是为什么
using namespace std;
可能是一个坏主意的一个例子。std
中有足够多的随机内容(C++0x 添加了更多!),很可能会发生名称冲突。我建议您不要使用using namespace std;
,而是明确使用,例如using std::transform;
。using namespace std;
instructs the compiler to search for undecorated names (ie, ones without::
s) instd
as well as the root namespace. Now, thetolower
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
.There's also a
std::tolower
however, which takes two parameters. When you haveusing namespace std;
and attempt to usetolower
, the compiler doesn't know which one you mean, and so it' becomes an error.As such, you need to use
::tolower
to specify you want the one in the root namespace.This, incidentally, is an example why
using namespace std;
can be a bad idea. There's enough random stuff instd
(and C++0x adds more!) that it's quite likely that name collisions can occur. I would recommend you not useusing namespace std;
, and rather explicitly use, e.g.using std::transform;
specifically.