Cpp - class using

Introduction

You can access to the elements of a namespace via a using declaration or using directive.

In this case, you do not need to repeatedly quote the namespace.

using Declarations

A using declaration makes an identifier from a namespace visible in the current scope.

using myLib::calculate;    // Declaration 

You can then call the function calculate() from the myLib namespace.

double erg = calculate( 3.7, 5);  

using Directive

The using directive allows you to import all the identifiers in a namespace.

using namespace myLib; 

This statement allows you to reference the identifiers in the myLib namespace directly.

If myLib contains an additional namespace and a using directive, this namespace is also imported.

C++ header files without file extensions declares the global identifiers in the standard namespace std.

The using directive imports any required identifiers to the global scope:

      
#include <string> 
using namespace std; 

Demonstrates the use of using-declarations and using-directives.

Demo

#include <iostream>      // Namespace std 

void message()           // Global function ::message() 
{ 
    std::cout << "Within function ::message()\n"; 
} 

namespace A /*from  w ww.j  av a2  s . c o m*/
{ 
    using namespace std; // Names of std are visible here 
    void message()       // Function A::message() 
    { 
      cout << "Within function A::message()\n"; 
    } 
} 

namespace B 
{ 
    using std::cout;      // Declaring cout of std. 
    void message(void);   // Function B::message() 
} 
void B::message(void)    // Defining B::message() 
{ 
    cout << "Within function B::message()\n"; 
} 

int main() 
{ 
    using namespace std;  // Names of namespace std 
    using B::message;     // Function name without braces! 
    A::message(); 
    message();           // ::message() is hidden because 
                         // of the using-declaration. 
    ::message();         // Global function 
    return 0; 
}

Result

Related Topic