Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) NamespaceExample1

 

BoostQt CreatorLubuntu

 

namespace example 1: scopes is a namespace example.

In the example, three versions of the function SayHello reside in different namespaces: loud, soft and the global namespace.

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppNamespaceExample1/CppNamespaceExample1.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp

QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++

unix {
  QMAKE_CXXFLAGS += -Werror
}

 

 

 

 

 

./CppNamespaceExample1/main.cpp

 

#include <iostream>

namespace loud
{
  void SayHello() { std::cout << "HELLO WORLD!\n"; }
}

//SayHello in the global namespace, ::SayHello()
void SayHello() { std::cout << "Hello world\n"; }

namespace soft
{
  void SayHello() { std::cout << "H.e.l.l.o w.o.r.l.d...\n"; }
}

int main()
{
  loud::SayHello();     //Call loud::SayHello
  ::SayHello();         //Explicity call SayHello from global namespace
  SayHello();           //Call the SayHello used, which is ::SayHello by default
  using soft::SayHello; //Start using soft::SayHello
  SayHello();           //Call the SayHello used, which is soft::SayHello now
  soft::SayHello();     //Call soft::SayHello
}

/* Screen output:

HELLO WORLD!
Hello world
Hello world
H.e.l.l.o w.o.r.l.d...
H.e.l.l.o w.o.r.l.d...
Press <RETURN> to close this window...

*/

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml