命名空间【C++入门】

我们在看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;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值