Export (0) Print
Expand All

using Directive

The using directive allows the names in a namespace to be used without the namespace-name as an explicit qualifier. Of course, the complete, qualified name can still be used to improve readability.

Grammar

using-directive:
using namespace ::opt nested-name-specifieropt namespace-name

Note the difference between the using directive and the using declaration : the using declaration allows an individual name to be used without qualification, the using directive allows all the names in a namespace to be used without qualification.

Example

// using_directive.cpp
// compile with: /EHsc
#include <iostream>

int main()
{
   std::cout << "Hello ";
   using namespace std;
   cout << "World." << endl;
}

Output

Hello World.

If a local variable has the same name as a namespace variable, the namespace variable is hidden. It is an error to have a namespace variable with the same name as a global variable.

The std namespace

The ANSI/ISO C++ standard requires you to explicitly declare the namespace in the standard library. For example, when using iostream.h, you do not have to specify the namespace of cout in one of the following ways:

  • std::cout (explicitly)
  • using std::cout (using declaration)
  • using namespace std (using directive)

Visual C++ continues to support the use of older header filenames with the .h extension. Such usage does not require invocation of the std namespace described above.

Managed Extensions for C++

The following sample shows how to allow names in a .NET Framework SDK base class library namespace to be used without the namespace-name as an explicit qualifier.

// using_directive2.cpp
// compile with: /LD /clr
#using <mscorlib.dll>
using namespace System::Reflection;
[assembly:AssemblyDescriptionAttribute("test")];

See Also

Namespaces | C++ Keywords

Show:
© 2014 Microsoft