C++ using namespace STD usage in depth analysis

  • 2020-04-02 01:22:30
  • OfStack

A:
< iostream > and < Iostream. H > It's not the same, it doesn't have a suffix, and in fact, as you can see in your compiler include folder, it's two files, and when you open the files, you'll see that the code is different.

The header file with the suffix. H C ++ standard has been explicitly unsupported. Earlier implementations defined the standard library functionality in the global space and declared it in the header file with the. H suffix.

Therefore, when used < Iostream. H > , which is equivalent to calling library functions in c, using the global namespace, the early c++ implementation.

When using < iostream > When the header file does not define a global namespace, it must use namespace STD; So you can use cout correctly.

2:
Called namespace, is a variety of visible scope of indicator identifier.

All the identifiers in the C++ standard library are defined in a namespace named STD.

Because of the concept of namespace, there are three options for using any identifier of the C++ standard library:

1. Specify the identifier directly. For example, STD ::ostream instead of ostream. The full statement is as follows:
STD: : cout < < STD: : hex < < 3.4 < < STD: : endl;

2. Use the using keyword.
Using STD: : cout;
Using STD: : endl;

The above procedure can be written as
cout < < STD: : hex < < 3.4 < < Endl;

3. The most convenient is to use the using namespace STD;

Such as:
# include < iostream >
# include < sstream >
# include < The string >
Using namespace STD.

All identifiers defined in the namespace STD are thus valid (exposed). As if they were declared as global variables. The above statement can be written as follows:
cout < < hex < < 3.4 < < Endl;
Because the standard library is so large, the programmer will most likely choose a class name or function name that is the same as a name in the standard library. So to avoid name conflicts caused by this situation, everything in the standard library is placed in the namespace STD. But that raises a new problem. Countless pieces of original C++ code rely on functionality in pseudo-standard libraries that have been used for years, all in global space.  

So there you have it < Iostream. H > and < iostream > And so on, one for compatibility with the old C++ code, one for support of the new standard.

The namespace STD encapsulates the name of the standard library, which is generally not ".h" to distinguish it from previous header files


Related articles: