The std Namespace. McGraw-Hill The Complete Reference Fourth Edition
Reklama
Reklama
C h a p t e r 2 3 : N a m e s p a c e s , C o n v e r s i o n F u n c t i o n s , a n d O t h e r A d v a n c e d T o p i c s
601 using namespace NS1;
/* Now that NS1 is in view, NS2 can be used to refer to j. */ cout << i * NS2::j;
} return 0;
This program produces the following output:
19 10
190
Here, the namespace NS2 is nested within NS1. Thus, when the program begins, to refer to j, you must qualify it with both the NS1 and NS2 namespaces. NS2 by itself is insufficient. After the statement using namespace NS1; executes, you can refer directly to NS2 since the using statement brings NS1 into view.
Typically, you will not need to create namespaces for most small to medium-sized programs. However, if you will be creating libraries of reusable code or it you want to ensure the widest portability, then consider wrapping your code within a namespace.
The std Namespace
Standard C++ defines its entire library in its own namespace called std. This is the reason that most of the programs in this book include the following statement: using namespace std;
This causes the std namespace to be brought into the current namespace, which gives you direct access to the names of the functions and classes defined within the library without having to qualify each one with std::.
Of course, you can explicitly qualify each name with std:: if you like. For example, the following program does not bring the library into the global namespace.
// Use explicit std:: qualification.
602
C + + : T h e C o m p l e t e R e f e r e n c e
#include <iostream> int main()
{ int val; std::cout << "Enter a number: "; std::cin >> val; std::cout << "This is your number: "; std::cout << std::hex << val;
} return 0;
Here, cout, cin, and the manipulator hex are explicitly qualified by their namespace.
That is, to write to standard output, you must specify std::cout; to read from standard input, you must use std::cin; and the hex manipulator must be referred to as std::hex.
You may not want to bring the standard C++ library into the global namespace if your program will be making only limited use of it. However, if your program contains hundreds of references to library names, then including std in the current namespace is far easier than qualifying each name individually.
If you are using only a few names from the standard library, it may make more sense to specify a using statement for each individually. The advantage to this approach is that you can still use those names without an std:: qualification, but you will not be bringing the entire standard library into the global namespace. For example:
// Bring only a few names into the global namespace.
#include <iostream>
// gain access to cout, cin, and hex using std::cout; using std::cin; using std::hex; int main()
{ int val;
Preuzimanje
Reklama