问题
Why is this?
transform(theWord.begin(), theWord.end(), theWord.begin(), std::tolower);
- does not work
transform(theWord.begin(), theWord.end(), theWord.begin(), tolower);
- does not work
but
transform(theWord.begin(), theWord.end(), theWord.begin(), ::tolower);
- does work
theWord is a string. I am using namespace std;
Why does it work with the prefix ::
and not the with the std::
or with nothing?
thanks for your help.
回答1:
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.
来源:https://stackoverflow.com/questions/6658767/c-name-space-confusion-std-vs-vs-no-prefix-on-a-call-to-tolower