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

use*_*913 5 c++ namespaces 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(), ::tolower); - 确实有效

theWord是一个字符串.我是using namespace std;

为什么它与前缀一起使用::而不是与std::或没有?

谢谢你的帮助.

bdo*_*lan 16

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

std::tolower然而,还有一个需要两个参数.当您拥有using namespace std;并尝试使用时tolower,编译器不知道您的意思,因此它会变成错误.

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

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

  • 从技术上讲,OP的:: tolower()仅由于实现细节而存在.为了保证C库的`tolower`在全局命名空间中,必须包含`<ctype.h>`而不是`<cctype>`(参见`D.5 [depr.c.headers]/2`) (4认同)