【问题标题】:C++ name space confusion - std:: vs :: vs no prefix on a call to tolower?C++ 名称空间混淆 - std:: vs :: vs 调用 tolower 时没有前缀?
【发布时间】:2011-10-03 06:42:00
【问题描述】:

这是为什么?

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:: 或什么都没有?

感谢您的帮助。

【问题讨论】:

  • 你包含哪些头文件?
  • #include <cstdlib> #include <fstream> #include <iterator> #include <algorithm> #include <cctype> #include <vector> #include <sstream>

标签: c++ namespaces name-decoration


【解决方案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; 具体来说。

【讨论】:

  • 所以 ::tolower 告诉编译器在根名称空间中查找,而 std::tolower 告诉编译器在标准名称空间中查找。那是对的吗?在这种情况下,我想要根名称空间的 tolower 而不是标准名称空间。
  • 对。或者你可以停止使用using namespace std 并且 tolow 会正常工作:)
  • 从技术上讲,OP 的 ::tolower() 仅由于实现细节而存在。为了保证 C 库的 tolower 在全局命名空间中,必须包含 <ctype.h> 而不是 <cctype>(参见 D.5[depr.c.headers]/2
  • 所以如果一个同时包含 ,std::tolower 将来自哪一个?
  • @HayriUğurKoltuk 取决于。它们的定义不同,因此您将两者兼而有之。
猜你喜欢
  • 2023-03-14
  • 2015-10-13
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 2016-06-09
  • 2017-06-10
相关资源
最近更新 更多