(一)引入命名空间

我们经常会看到如下的用法:

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int main()
{
cout << "hello, world"<< endl;
return 0;
}

上述代码中使用了using namespace std; 若不加这句话,主函数中的cout就无法使用,原因在于cout类的实现在std中(标准输入输出 命名空间)

若删去using namespace std;,那就需要在cout 和 endl前加上std::

1
2
3
4
5
6
#include <iostream>
int main()
{
std::cout << "hello, world"<< std::endl;
return 0;
}

为了解决命名冲突的问题,C++提供了命名空间的作用域的机制;


(二)命名空间的使用

(1)定义基本语法

1
2
3
4
5
namespace 命名空间名
{

}

(2)使用

错误写法:

1
2
3
4
5
6
7
8
9
using namespace jiege;
namespace jiege
{
void Print()
{
std::cout << "jiege" << std::endl;
}
}


正确写法:

1
2
3
4
5
6
7
8
namespace jiege
{
void Print()
{
std::cout << "jiege" << std::endl;
}
}
using namespace jiege;

(3)栗子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

namespace jiege
{
void Print()
{
std::cout << "jiege" << std::endl;
}
}

namespace awei
{
void Print()
{
std::cout << "awei" << std::endl;
}
}

int main()
{
jiege::Print();
awei::Print();

return 0;
}

结果:
在这里插入图片描述