我们在看C++代码的时候,常常会看到一行这样的代码
using namespace std;
那它是干嘛的呢? 其实这就是我们所说的命名空间,因为命名冲突问题而产生的
命名冲突问题
1、我们自己定义的变量、函数可能会和库里面重名冲突;
2、做大项目时,需要多人协作,两个同事写的代码,命名冲突;
C语言没有办法很好的解决这个问题,所以,C++提出了一个新语法,命名空间
看如下这段代码
#include<stdio.h>
#include<stdlib.h>
int rand = 0;
int mian()
{
printf("hello world");
printf("%d", rand);
}
报错了,为什么呢?观察报错信息,重定义!还是个函数,不是,我没有写函数啊!?
通过查看头文件我们可以知道,stdlib.h
这个头文件里面有rand()
的函数
So,我们定义一个叫cyj
的命名空间 - - 域
这里的::
是域作用限制符,表示取左边这个域里面的,在这个域里面去找,
::a
左边为空表示找的是全局变量a,而单独的一个a取的是局部变量
1、命名空间可以定义变量/函数/类型
namespace cyj
{
int rand = 10;
int Add(int left, int right)
{
return left + right + 10;
}
struct Node
{
struct Node* next;
int val;
};
}
2. 命名空间可以嵌套
namespace cyj
{
int rand = 10;
int Add(int left, int right)
{
return left + right + 10;
}
struct Node
{
struct Node* next;
int val;
};
}
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;
}
}
}
int main()
{
cyj::rand = 10;
struct cyj::Node node;
cyj::Add(1, 2);
N1::Add(1, 2);
N1::N2::Sub(3, 4);
struct cyj::ListNode ln;
cyj::ListInit();
return 0;
}
3. 其他用法
把整个命名空间展开 – 展开到全局了
using namespace cyj;
单独展开某一个,其他不展开
using szy::ListNode;
int main()
{
struct ListNode ln;
szy::ListInit();
printf("%d\n", szy::rand);
return 0;
}
C++库的实现定义在一个叫std的命名空间中
#include <iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
return 0;
}
#include <iostream>
//using namespace std;
// 常用的展开
using std::cout;
using std::endl;
int main()
{
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
cout << "hello world\n";
printf("hello world\n");
int i = 10;
double d = 1.11;
// 自动识别类型
cout << i << " " << d << endl;
return 0;
}