
1.为什么有命名空间?
namespace为了解决多人合作中名字(标志符)重复的问题。
2.命名空间的格式与注意事项。
namespace A//A是空间名字
{
int a=10;//可以定义变量也可以声明函数
void func()
{
}
}
namespace one
{
int a=10;
namespace two//命名空间可以嵌套命名空间
{
int a=5;
}
}
namespace A
{
int a=10;
void func()
{
}
}
namespace A//命名空间是开放的可以再增加
{
int b=5;
}
3::作用域运算符
namespace one
{
int a=8;
namespace two//命名空间嵌套
{
int a=5;
}
}
int a=20;//全局变量存储在静态存储区,不清除
int main(int argc, char **argv)
{
using std::cout,std::endl;
int a=10;//局部变量存储在栈中,程序结束自动清除
cout<<"a="<
运算结果如下图
4.命名空间必须在使用前加入,即在代码中放在引用空间变量函数的前面。
void test()
{
cout<
5.没有名字的命名空间
namespace//类似与static int d=50;静态的全局变量
{
int d=50;
}
}
//使用时此项目中直接使用,但是其他项目无法使用
6.命名空间可以取别名
namespace A
{
int a=10;
void func()
{
}
namespace A
{
int b=5;
}
void test3()
{
// 新名字 旧名字
namespace nameA = A;
std::cout<
输出结果为10。
7.分文件编写代码时,如果.h中有两个命名空间,但是里面的函数成员或函数变量同名时,在.cpp中实现函数时,需要加上命名空间。
//test.h//
#include
using namespace std;
namespace myMaker1
{
void func();
}
namespace myMaker2
{
void func();
}
//mian.cpp//
#include
#include "test.h"
void myMaker1::func()
{
cout<<"test"<
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)