c++的命名空间

命名空间

一.c++的关键字

c++中一共有63个关键字

关键字 1 1 1 1 1
asm do if return try continue
auto double inline short typedef for
bool dynamic_cast int signed typeid public
break else long sizeof typename throw
case enum mutable static union wchar_t
catch explicit namespace static_cast unsigned default
char export new struct using friend
class extern operator switch virtual register
const false private template void true
const_cast float protected this volatile while
delete goto reinterpret_cast

二.命名空间

在c++中使用命名空间的目的是对标识符的名称进行本地化,以避免命名冲突或名字污染,namespace关键字的出现就是针对这种问题的

c 复制代码
int rand = 10;
int main()
{
	printf("%d\n", rand);
	return 0;
}

这个代码在vs下就会报错

2.1 命名空间定义

定义命名空间需要使用namespace关键字,后面在加上{}就行

c 复制代码
namespace zhang
{
	int a=10;

}

int main()
{
	cout<<zhang::a << endl;
	return 0;
}

在命名空间中我们可以可以定义变量/函数/类型,就当main函数使用,当然我们也可以嵌套命名空间

cpp 复制代码
namespace zy
{
	namespace zz
	{
		namespace yy
		{
			int rand = 0;
		}
	}
}

int main()
{
	cout << "hello world" << endl;

	//:: 域作用限定符
	cout  << zy::zz::yy::rand << endl;
	return 0;
}

2.1 命名空间的使用

命名空间的使用有三种方式

2.1.1加命名空间名称及作用域限定符

c 复制代码
int main()
{
	cout<<zhang::a << endl;
	return 0;
}

2.1.2使用using将命名空间中某个成员引入

c 复制代码
using zy::zz::yy::rand;

int main()
{
	cout  << zy::zz::yy::rand << endl;
	return 0;
}

三.标准命名空间std

标准C++库中的所有标识符都是在一个名为std的命名空间中定义的,或者说标准头文件中的函数、类、对象和模板实在命名空间std中定义的。一般用using namespace语句对命名空间std进行声明,这样可以不必对每个命名空间成员一一进行处理,在文件的开头加入如下语句:

using namespace std;

相关推荐
不可描述的两脚兽几秒前
Redis 快记
java·数据库·redis
sanggou6 分钟前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
普通网友10 分钟前
C++与Qt图形开发
开发语言·c++·算法
AA陈超34 分钟前
UE5笔记:GetWorld()->SpawnActorDeferred()
c++·笔记·学习·ue5·虚幻引擎
yue00841 分钟前
C# 更改窗体样式
开发语言·c#
普通网友1 小时前
C++中的适配器模式
开发语言·c++·算法
风闲12171 小时前
Qt源码编译记录
开发语言·qt
Felix_XXXXL1 小时前
mysql查看binlog日志
java·后端
无敌最俊朗@1 小时前
力扣hot100-160-相交链表
c++
leonardee1 小时前
Plugin ‘mysql_native_password‘ is not loaded`
java·后端