主要用途:用来解决命名冲突的问题。
1.命名空间下 可以放 函数、变量、结构体、类
2.命名空间必须定义在 全局作用域 下
3.命名空间可以嵌套命名空间
4.命名空间是开放的,可以随时往原先的 命名空间 添加内容
5.匿名(无名)命名空间
相当于写了 static int m_C;static int m_D;
只能在当前文件夹使用
6.命名空间可以起别名
game1.h
#pragma once
#include<iostream>
using namespace std;
namespace LOL {
void goAtk();
}
game1.cpp
#include "game1.h"
void LOL::goAtk() {
cout << "LOL Attack." << endl;
}
game2.h
#pragma once
#include<iostream>
using namespace std;
namespace KingGlory {
void goAtk();
}
game2.cpp
#include "game2.h"
void KingGlory::goAtk() {
cout << "KingGlory Attack." << endl;
}
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "game1.h"
#include "game2.h"
using namespace std;
int atk = 200;
void test() {
int atk = 100;
cout << "局部攻击力:" << atk << endl;
//双冒号::为作用域运算符,引用全局作用域
cout << "全局攻击力:" << ::atk << endl;
}
namespace A {
void func();
int m_A = 20;
struct Person {
};
class Animal {};
namespace B {
int m_A = 10;
}
}
void test02() {
cout << "作用域B下的m_A为:" << A::B::m_A << endl;
}
//此A命名空间会与上定义的A合并
namespace A {
int m_B = 1000;
}
void test03() {
cout << "A::下的m_A为:" << A::m_A << ",m_B为:" << A::m_B << endl;
}
//相当于写了 static int m_C;static int m_D;
//只能在当前文件夹使用
namespace {
int m_C = 0;
int m_D = 0;
}
namespace veryLongName {
int m_A = 0;
}
void test04() {
//起别名
namespace veryShortName = veryLongName;
cout <<"veryLongName:" << veryLongName::m_A << endl;
cout <<"veryShortName:" << veryShortName::m_A << endl;
}
int main() {
/*
cout << "Hello World!" << endl;
system("pause");
test();
*/
LOL::goAtk();
KingGlory::goAtk();
test02();
test03();
test04();
return EXIT_SUCCESS;
}