简体   繁体   中英

using namespace in c++

I have come to understand why using namespace std; is considered bad practice in c++ but let's consider for example 2 ( hypothetical ) libraries "std" and "sfd" , both of them contain a function "run()".
would the following be okay or is it still a problem :
( if i want to call "run()" from "std" )

   using namespace std;  
   using namespace sfd;  
   int main(){
       std::run();
}  

( if i want to call "run()" from "sfd" )

   using namespace std;
   using namespace sfd;
   int main(){
   sfd::run();
}  

The main purpose of using using namespace whatever; is to avoid typing the name of that namespace (like std and sfd ) every time you want to have access to one of its members (for reasons such as saving time and also making the code look a bit cleaner). There is no problem with your solution though. It works.

But again, why would you want to use using namespace std; at the top of your source file if you're eventually going to add std:: to whichever function that needs it?

You can also write using namespace std; in a (function, loop, etc) scope so that it doesn't pollute the whole namespace of that particular source file.

There is no problem because you are using qualified names in the function calls.

A program would be ill-formed if you used the unqualified function name in its call like

run();

In this case there would be ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM