C++学习
namespace使用
game1.h
#include<iostream>
namespace B
{
void atk();
}
game2.h
#include <iostream>
namespace A
{
void atk();
}
game1.cpp
#include <iostream>
#include "game2.h"
using namespace std;
void A::atk()
{
cout << "A 攻击" << endl;
}
game2.cpp
#include<iostream>
#include"game2.h"
void B::atk()
{
std::cout << " B 攻击力" <<std::endl;
}
main.cpp
#include<iostream>
#include"game1.h"
#include"game2.h"
using namespace std;
int atk = 200;
//0.双冒号 :: 作用域算符, 不写作用域就是全局
void test()
{
cout << "攻击力 = " << atk << endl;
cout << "全局攻击力 = " << ::atk << endl;
}
//1.命名空间下可放函数,变量,类等
namespace C
{
struct{};
class{};
int f = 100;
namespace D {
int f = 200;
}
}
namespace C
{
int g = 300;
}
//2.namespace 可以用来解决命名冲突
void test0()
{
A::atk();
B::atk();
}
//3. 命名空间作用域全局
//4. 命名空间可以嵌套命名空间
void test1()
{
cout << "作用域C中f= " << C::f << endl << "作用域D中f= " << C::D::f << endl;
}
//5.命名空间是开放的,可随时往命名空间添加内容
void test2()
{
cout << "作用域C中 g = " << C::g << endl;
}
//6.无名,匿名命名空间
namespace
{
int h = 0;//无名命名空间, 相当于 static int h;只能在当前文件内使用
}
//7.命名空间可以起别名
void test3()
{
namespace O = C;
}
int main()
{
test();
test0();
test1();
test2();
return 0;
}
结论:
- 双冒号 :: 作用域算符, 不写作用域就是全局。
- 命名空间下可放函数,变量,类等。
- namespace 可以用来解决命名冲突.
- 命名空间作用域全局.
- 命名空间可以嵌套命名空间
- 命名空间是开放的,可随时往命名空间添加内容
- 无名命名空间, 相当于 static int 只能在当前文件内使用
- 命名空间可以起别名