本文主要是介绍C++中namespace的用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我们在现实的项目开发中一般会有着大量的代码,而且代码都是多人编写的,也许一个项目会有10个功能,每一个人都要完成一个功能。但是敲过代码的都知道,一般在编写程序的时候如果多人没有实现约定去完成,那就会出现代码冲突的情况,那么,为了解决这样的冲突,我们C++中使用了命名空间
namespace用法
我们上个代码演示一下:
#include <iostream>
#include<test.h>using namespace std;namespace A{int x= 10;void fun1(){
cout<<"this is namespace A"<<endl;
}
}int main()
{cout << A::x <<endl;A::fun1();return 0;
}
namespace嵌套用法
#include <iostream>
#include<test.h>using namespace std;namespace a {
namespace b {
int a = 10;
}
}int main()
{cout << a::b::a << endl;return 0;
}
分文件命名空间
当然,在项目过于庞大的时候如果我们写的命名空间太多的话,就会和老太太的裹脚布一样,又臭又长!!!!所以我们可以新建两个文件test.h和test.cpp我们在.h中定义,在.cpp中使用。
test.h:
#ifndef TEST_H//防止被多包含
#define TEST_H
//声名一个命名空间
namespace myspace {//声名函数
void func1();
void func2(int x);
}namespace student_info_guanli {
void fun1();
void fun2();
}#endif // TEST_H
test.cpp:
#include"test.h"
#include"iostream"
using namespace std;
//实现myspace
void myspace::func1(){cout << "this is func1"<<endl;}void myspace::func2(int x){cout << "func" << x << endl;
}namespace S_I_G = student_info_guanli;void S_I_G::fun1(){cout << "this is S_I_G's new namespace"<<endl;
}void S_I_G::fun2(){cout << " this is student_info_gunali new namespace" <<endl;
}
main.cpp
#include <iostream>
#include<test.h>using namespace std;namespace a {
namespace b {
int a = 10;
}
}int main()
{myspace::func1();myspace::func2(100);cout << a::b::a << endl;student_info_guanli::fun1();student_info_guanli::fun2();return 0;
}
命名空间的简写:
在我们的项目中一般我们起的命名空间的名字会很长(为了让别人看懂)我们一般会设置的比较长且全面一点比如:student_info_guanli;但是我就是挺随意,就是s_i_g,我可以看懂,但是别人看不懂,所以我们可以起个别名。
namespace S_I_G = student_info_guanli;void S_I_G::fun1(){cout << "this is S_I_G's new namespace"<<endl;
}void S_I_G::fun2(){cout << " this is student_info_gunali new namespace" <<endl;
}
我们可以在.cpp文件中调用的时候写成别名,然后再main中使用的时候还是使用全名哦!!
好嘞!下课!!!
这篇关于C++中namespace的用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!