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.
Operating system(s) or programming environment(s)
- Lubuntu 15.04 (vivid)
- Qt Creator 3.1.1
- G++ 4.9.2
Libraries used:
- STL: GNU ISO C++ Library, version 4.9.2
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 }
#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... */