#include <iostream>
#include "game1.h"
#include "game2.h"
// 1.resolve name conflicts
void test01()
{
LOL::goAttack();//game1.h
KingGlory::goAttack();//game2.h
}
//2. you can put variables, functions, structures, classes in namespace.
namespace A{
int m_A;
void func();
struct Person{};
class Animal{};
}
void test02()
{
// 3.namespace must be declared under the global scope.
// namespace definition is not allowed in local fields.
#if 0
namespace B{
int m_B;
}
#endif
}
//4. namespace can be nested within namespace
namespace B{
int m_A = 10;
namespace C{
int m_A = 20;
}
}
void test03()
{
std::cout << "B_m_A = " << B::m_A << std::endl;
std::cout << "C_m_A = " << B::C::m_A << std::endl;
}
// 5.namespace is open,and content can be added at any time.
namespace B
{
int m_B = 100;
} // namespace B
void test04()
{
std::cout << "B_m_A = " << B::m_A << std::endl;
std::cout << "B_m_B = " << B::m_B << std::endl;
}
// 6.namespace can be anonymous
namespace{
// Equivalent to static
int m_C = 333;//static m_C
int m_D = 444;//static m_D
}
void test05()
{
std::cout << "m_C = " <<m_C <<std::endl;
std::cout << "m_D = " << ::m_D << std::endl;
}
//7. namespaces can have aliases.
namespace LongName{
int m_E = 10000;
}
void test06()
{
namespace ShortName = LongName;
std::cout << "namespace aliases:" << std::endl;
std::cout << "ShortName::m_E::" <<ShortName::m_E << std::endl;
}
int main()
{
test01();
test03();
test04();
test05();
test06();
return EXIT_SUCCESS;
}
见代码
namespace的7种用法/功能