// game1.h
#include<iostream>
using namespace std;
namespace LOL
{
void goAtk();
}
// game1.cpp
#include "game1.h"
void LOL::goAtk()
{
cout << "LOL的攻击实现" << endl;
}
// game2.h
#include<iostream>
using namespace std;
namespace KingGlory
{
void goAtk();
}
// game2.cpp
#include "game2.h"
void KingGlory::goAtk()
{
cout << "王者荣耀的攻击实现" << endl;
}
/*
namespace 命名空间主要用途: 用来解决命名冲突的问题
1. 命名空间下,可以放函数、变量、结构体、类
2. 命名空间必须定义在全局变量下
3. 命名空间可以嵌套命名空间
4. 命名空间是开放的,可以随时往命名空间中添加内容
5. 匿名命名空间
6. 命名空间可以起别名
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include "game1.h"
#include "game2.h"
void test01()
{
LOL::goAtk(); // LOL的攻击实现
KingGlory::goAtk(); // 王者荣耀的攻击实现
}
// namespace 命名空间主要用途: 用来解决命名冲突的问题
// 1. 命名空间下,可以放函数、变量、结构体、类
namespace A
{
void func();
int a = 10;
struct Animal1
{
};
class Animal2
{
};
namespace B
{
int a = 20;
}
}
// 2. 命名空间必须定义在全局变量下
// 3. 命名空间可以嵌套命名空间
// 4. 命名空间是开放的,可以随时往命名空间中添加内容
namespace A // 此命名空间会与上面的命名空间A合并
{
int b = 15;
}
void test02()
{
cout << "作用域A下面的a是" << A::a << " 作用域A下面的b是" << A::b << endl; // 10, 15
}
// 5. 匿名命名空间
namespace
{
int c = 0;
int d = 1;
}
// 当写了匿名命名空间相当于写了 static c; static d; 只能在当前文件中使用
// 6. 命名空间可以起别名
namespace veryLongName
{
int e = 2;
}
void test03()
{
namespace veryShortName = veryLongName;
cout << veryLongName::e << endl; // 2
cout << veryShortName::e << endl; // 2
}
int main()
{
cout <<"作用域B下面的a是 "<< A::B::a << endl; // 20
test01();
test02();
cout << c << endl; // 0
test03();
return EXIT_SUCCESS;
}