C++ namespace

1. 命名空间的创建

1. 显式创建

namespace [name] {content}
命名空间中可以只声明变量,在外部再进行实现

1
2
3
4
// useless.h 
namespace useless {
void FOO();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// main.h
#include <iostream>
#include "useless.h"
using namespace useless;
namespace s {
int x;
void funcA() {
printf("111");
}
}
void useless::FOO() {
printf("Foo");
}
int main() {
s::funcA();
FOO();
}

2. 内联命名空间

方便进行更新,后面的会对前面的函数进行覆盖。

1
2
3
4
5
6
7
8
9
#include <stdio.h>
namespace old_new {
namespace v1 {
void foo() {printf("V1");}
}
namespace v2 {
void foo() {printf("V2");}
}
}

2. 使用命名空间中的元素

1. 完整使用

如下所示创建一个对象

1
useless::classA obj1;

2. 引用对象

将命名空间中的classA引入进来,后面使用的时候可以进行直接的调用

1
using useless:classA ;

3. 引入整个命名空间

将整个命名空间引入进来就可以使用其中的所有成员

1
using namespace useless;