c++中的命名空间用于组织项目中的类,以方便处理应用程序结构。
对于访问命名空间的类,我们需要使用namespacename::classname
。 可以使用 using
关键字,所以不必一直使用完整的名称。
在c++中,全局命名空间是根命名空间。 global::std
总是引用c++ 框架的命名空间“std
”。
下面来看看看包含变量和函数的命名空间的一个简单例子。
#include <iostream>
using namespace std;
namespace first {
void sayhello() {
cout<<"hello first namespace"<<endl;
}
}
namespace second {
void sayhello() {
cout<<"hello second namespace"<<endl;
}
}
int main()
{
first::sayhello();
second::sayhello();
return 0;
}
执行上面代码,得到以下结果 -
hello first namespace
hello second namespace
c++命名空间示例:通过使用 using 关键字
下面来看看看另一个命名空间的例子,使用“using
”关键字,这样就不必使用完整的名称来访问命名空间程序。
#include <iostream>
using namespace std;
namespace first{
void sayhello(){
cout << "hello first namespace" << endl;
}
}
namespace second{
void sayhello(){
cout << "hello second namespace" << endl;
}
}
using namespace first;
int main () {
sayhello();
return 0;
}
执行上面代码,得到以下结果 -
hello first namespace