命名空间
C语言没办法解决类似这样的命名冲突问题,所以C++提出了namespace来解决
#include <stdio.h>
#include <stdlib.h>
int rand = 10;
// C语言没办法解决类似这样的命名冲突问题,所以C++提出了namespace来解决
int main()
{
printf("%d\n", rand);
return 0;
}
// 编译后后报错:error C2365: “rand”: 重定义;以前的定义是“函数”
命名空间使用
一个命名空间就定义了一个新的作用域,命名空间中的所有内容都局限于该命名空间中
更多的域
类域
命名空间域
局部域
全局域
局部域优先全局域
展开了命名空间,编译时就会去所展开的命名空间寻找
这里是全局域和命名空间域的同名变量发生冲突
所以可以指定展开空间域
命名空间可以嵌套
// 命名空间可以嵌套
// test.cpp
namespace N1
{
int a;
int b;
int Add(int left, int right)
{
return left + right;
}
namespace N2
{
int c;
int d;
int Sub(int left, int right)
{
return left - right;
}
}
}
同一个工程中允许存在多个相同名称的命名空间,编译器最后会合成同一个命名空间中。
// ps:一个工程中的test.h和上面test.cpp中两个N1会被合并成一个
工程中使用展开 和 日常使用展开常用的
日常使用练习 随意展开
工程中指定展开
std::cout << "hello world" << std::endl;
展开常用的
// 展开某个:把常用展开
using std::cout;
using std::endl;
int main()
{
int x = 10;
// << 流插入运算符
cout << "hello world" << x << '\n' << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
return 0;
}