【C++札记】命名空间(namespace)
介绍
命名空间可以解决程序中的同名冲突,尤其大型项目多人开发中经常用到。比如我们使用C++的标准输出std::cout就使用了std命名空间。
使用作用域符::
#include <iostream>
using namespace std;
int var = 10;
void foo()
{
cout << "this is foo" << endl;
}
int main()
{
int var = 20;
cout << var << endl; //输出局部变量
cout << ::var << endl; //输出全局变量
foo(); //不加作用域符
::foo(); //加作用域符
return 0;
}
命名空间会对全局的变量和函数进行作用域打包。
在某些第三方库中是有namespace的,因此我们在使用这些库的时,要确定是否使用using namespace来解除名字前缀。
使用语法:
namespace XXX
{
int var = 10;
class A
{
public:
...
};
} //没有分号
使用
假设有命名空间namespace Animal;
namespace Animal
{
int age = 10;
void action()
{
cout << "eatiing" << endl;
}
}
用法一:直接使用命名空间成员
cout << Animal::age << endl;
Animal::action();
用法二: using使用命名空间成员
using Animal::age;
cout << age << endl;
用法三:使用命名空间全部成员
using namespace Animal;
cout << age << endl;
foo();
同时命名空间也支持嵌
#include <stdio.h>
namespace XXX
{
class A
{
public:
void test()
{
printf("this is namespace XXX class A\n");
}
};
}
using namespace XXX;
int main()
{
A* p = new A();
p->test();
return 1;
}
相同的命名空间编译时会合并
#include <iostream>
using namespace std;
namespace Space {
int a = 10;
}
namespace Space {
int b = 20;
}
using namespace Space;
int main()
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
欢迎加群交流:C/C++开发交流

|
作者:蜗牛201 出处:https://www.cnblogs.com/woniu201/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |

浙公网安备 33010602011771号