为什么在C ++中使用ispunct()时不需要std ::? [英] Why std:: is not needed when using ispunct() in C++?
问题描述
#include <iostream>
#include <string>
#include <cctype>
using std::string;
using std::cin;
using std::cout; using std::endl;
int main()
{
string s("Hello World!!!");
decltype(s.size()) punct_cnt = 0;
for (auto c : s)
if (ispunct(c))
++punct_cnt;
cout << punct_cnt
<< " punctuation characters in " << s << endl;
}
似乎我可以在没有 std ::
的情况下使用 ispunct()
或使用std :: ispunct; 声明,但是我不能使用
std :: cout
或 std :: cin
可以做到这一点.为什么会这样?
It seems that I can use ispunct()
without std::
or declaring using std::ispunct;
but I can't do that with std::cout
or std::cin
. Why is this happening?
推荐答案
这意味着 ispunct
是全局名称空间的一部分,而不是 std
名称空间.这可能是因为 ispunct
是从C继承过来的功能之一(因此它位于 cctype
中).
It means ispunct
is part of the global namespace, rather than the std
namespace. This is probably because ispunct
is one of the functions brought over from C (hence it is in cctype
).
另一方面, cout
和 cin
是 std
名称空间的一部分,而不是全局名称空间.
On the other hand, cout
and cin
are part of the std
namespace, not the global namespace.
关于C的为什么原因是在全局名称空间中,而不是在 std
名称空间中,我认为这与允许C代码由C ++编译有关编译器进行了最少的更改,因为 C ++旨在与C兼容.
As to why things from C are in the global namespace instead of in the std
namespace, I believe it has to do with allowing C code to compile by a C++ compiler with minimal changes, since C++ aims to be compatible with C.
根据评论, ispunct
被允许,但不是必填,但必须位于全局命名空间中(但必填(位于 std
命名空间中)和< cctype>
中.但是,如果您包括了< ctype.h>
,则要求必须将 ispunct
置于全局命名空间中.
According to the comments, ispunct
is allowed, but not required, to be in the global namespace (but is required to be in the std
namespace), in <cctype>
. However, if you had included <ctype.h>
instead, ispunct
would be required to be in the global namespace.
这篇关于为什么在C ++中使用ispunct()时不需要std ::?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!