C++ namespace Definition

Introduction

You can define a namespace with these statements:

namespace myRegion
{
  // function definitions and declarations, global variables, templates, etc.
}

namespace calc// w  w w . j a v  a2s  .co m
{
  // This defines namespace calc
  // The initial code in the namespace goes here
}
namespace sort
{
  // Code in a new namespace, sort
}
namespace calc
{
  /* This extends the calc namespace
     Code in here can refer to names in the previous
     calc namespace block without qualification */
}

Using a namespace

#include <string>
#include <iostream>

namespace data//w  w  w.j  a  v  a2  s.co m
{
  extern const double pi {3.14159265};
  extern const std::string days[]
         {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
}

int main()
{
  std::cout << "pi has the value " << data::pi << std::endl;
  std::cout << "The second day of the week is " << data::days[1] << std::endl;
}



PreviousNext

Related