命名空间(namespace)

命名空间可以解决程序中的同名冲突,尤其大型项目多人开发中经常用到。比如我们使用C++的标准输出std::cout就使用了std命名空间。

使用作用域符::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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来解除名字前缀。

使用语法:

1
2
3
4
5
6
7
8
9
10
namespace XXX
{
int var = 10;

class A
{
public:
...
};
} //没有分号

使用

假设有命名空间namespace Animal;

1
2
3
4
5
6
7
8
namespace Animal 
{
int age = 10;
void action()
{
cout << "eatiing" << endl;
}
}

用法一:直接使用命名空间成员

1
2
cout << Animal::age << endl;
Animal::action();

用法二: using使用命名空间成员

1
2
using Animal::age;
cout << age << endl;

用法三:使用命名空间全部成员

1
2
3
using namespace Animal;
cout << age << endl;
foo();

同时命名空间也支持嵌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;
}

相同的命名空间编译时会合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×