C ++ Namespaces and Header Files

I saw codes with using namespace std; . Does this mean that if we use this, we do not need to include header files in the code, or if we do not use namespaces, does this mean that we must use std:: before each function, class?

+4
source share
3 answers

You must include header files and use namespaces.

Namespaces are contained in header files, io streams such as cin , cout are contained in namespaces . Thus, only if you include the header file can you use the namespace. Without using namespace std , you have to use the scope resolution statement every time you use these functions.

+7
source

using namespace std; means that all names from the std can be used without explicitly specifying their namespace (prefixed with std:: . That is, after using namespace std; , act both string and std::string . Without using namespace std; only std::string will work.

Header files must be included.

Please note that using using namespace often discouraged as it populates your code with all the names from this namespace and conflicts can occur.

+1
source
  using namespace std; 

This is actually not an ideal practice that I would apply in a professional code base. The reason is that it practically “expands” the std (packages in Java, if you want), where you are probably doing “Hello world” programming, etc., Not as serious as RT Embedded, Mission Critical or Safety Critical. For example, I work at Interservice / Industry Training and Simulation, where security / mission is often important; people would love to have a quiet word with me if I used several namespaces so openly. It doesn't concern the size of your program; it is more about good practice. Yes, if you have so many possibilities to use from the std , then you can probably just use it. The trade-off, as well as what I sometimes do, is:

 using std::endl; using std::string; using std::cout; using std::cin; // And something like that 

This "reveals" the ones you will need for this area, and still allows you to use:

 string myStr; cout << "Some cout" << endl; 

Like what you mentioned in your question. Why not give it a try?

The “good bit” is that if you follow the mentioned approach, it will also “update” your level of knowledge in C ++ namespaces and possible STLs.

I know that some people will say: “Well, it's hard work,” but for me it is a good compromise, to some extent. :)

DO NOT FORGET TO ADD NECESSARY FILE FILES, PLEASE :-)

+1
source

Source: https://habr.com/ru/post/1488427/


All Articles