0
Why do we use "using namespace std " in a c++ program
2 Antworten
+ 1
In general, a namespace is a container for a set of identifiers (also known as symbols, names). Namespaces provide a level of direction to specific identifiers, thus making it possible to distinguish between identifiers with the same exact name. For example, a surname could be thought of as a namespace that makes it possible to distinguish people who have the same given name. In computer programming, namespaces are typically employed for the purpose of grouping symbols and identifiers around a particular functionality.
The built in C++ library routines are kept in the standard namespace. That includes stuff like cout, cin, string, vector, map, etc. Because these tools are used so commonly, it's popular to add "using namespace std" at the top of your source code so that you won't have to type the std:: prefix constantly.
To avoid name collisions, C++ places the standard library stuff into a separate namespace whose name is std. (If it didn’t do this, everything would be defined in the global namespace, and we’d have the potential of name collisions.) That way, you can use all the libraries you want, and as long as each one puts its stuff into a separate namespace, you can explicitly pick and choose exactly what you want by specifying the namespace in which it is defined.
using namespace std;
pulls everything defined in the std namespace into the global namespace, as if it had not been defined inside a namespace at all. This makes it more convenient to access things that are defined in the std namespace, without having to use the scope resolution operator to qualify them. So, instead of having to say:
+ 1
To think of it more simply, a namespace is basically a collection of related classes/functions/etc... By using a namespace, it's more modular with its approach, as you can reuse that namespace in other projects, and it also assists with naming conflicts that may exist between two different sets.