为什么在C++中使用ispunct()时不需要std ::?

xia*_*ike 12 c++ std

#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;
}
Run Code Online (Sandbox Code Playgroud)

似乎我可以使用ispunct()没有std::或声明,using std::ispunct;但我不能用std::coutstd::cin.为什么会这样?

mad*_*tya 17

它意味着ispunct是全局命名空间的一部分,而不是std命名空间.这可能是因为ispunct从C带来的功能之一(因此它在cctype).

另一方面,coutcinstd命名空间的一部分,而不是全局命名空间.

编辑:

至于为什么来自C的东西是在全局命名空间而不是在std命名空间中,我认为它与允许C代码由C++编译器进行编译而变化很小,因为C++旨在与C兼容.

根据该意见,ispunct允许的,但不是必需的,是在全局命名空间(但要求是在std命名空间),在<cctype>.但是,如果您已包含<ctype.h>,ispunct需要位于全局命名空间中.

  • ``cctype>`需要将`ispunct`放入`std`并允许将它放在全局命名空间中. (2认同)