C++ name space confusion - std:: vs :: vs no prefix on a call to tolower?

前端 未结 1 966
抹茶落季
抹茶落季 2020-12-16 20:13

Why is this?

transform(theWord.begin(), theWord.end(), theWord.begin(), std::tolower); - does not work transform(theWord.begin(), theWord.end(),

相关标签:
1条回答
  • 2020-12-16 21:07

    using namespace std; instructs the compiler to search for undecorated names (ie, ones without ::s) in std as well as the root namespace. Now, the tolower you're looking at is part of the C library, and thus in the root namespace, which is always on the search path, but can also be explicitly referenced with ::tolower.

    There's also a std::tolower however, which takes two parameters. When you have using namespace std; and attempt to use tolower, the compiler doesn't know which one you mean, and so it' becomes an error.

    As such, you need to use ::tolower to specify you want the one in the root namespace.

    This, incidentally, is an example why using namespace std; can be a bad idea. There's enough random stuff in std (and C++0x adds more!) that it's quite likely that name collisions can occur. I would recommend you not use using namespace std;, and rather explicitly use, e.g. using std::transform; specifically.

    0 讨论(0)
提交回复
热议问题