10

为什么是这样?

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::或不一起使用?

谢谢你的帮助。

4

1 回答 1

20

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;

于 2011-07-12T02:12:30.910 回答