Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...