C++的命名空间域

目录

一、域作用限定符

二、编译器搜索变量、函数等的原则

三、命名空间域

四、命名空间域的嵌套使用

五、命名空间域展开与头文件展开的区别


一、域作用限定符

:: 即是域作用限定符,它的作用是指明一个标识符(变量、函数或类)来自哪一个作用域范围

二、编译器搜索变量、函数等的原则

1.先搜索局部变量,2.再搜索全局变量,3.最后搜索指定的命名空间域

三、命名空间域

用来解决变量、函数等重命名问题

如下,对于重命名的变量x编译器会报错

使用命名空间域解决这个问题

1.方法一:使用域作用限定符来指定变量的位置

cpp 复制代码
#include <iostream>

namespace bit1
{
	int a = 10;
}

namespace bit2
{
	int a = 20;
}

int main()
{
	printf("%d\n", bit1::a);

	printf("%d\n", bit2::a);
	return 0;
}

2.方法二: 命名空间域展开(展开后就无需使用域作用限定符来指定变量的位置)

cpp 复制代码
#include <iostream>

namespace bit1
{
	int a = 10;
	int b = 20;
	int c = 30;
}

using namespace bit1;
int main()
{
	printf("%d\n", a);
	printf("%d\n", b);
	printf("%d\n", c);
	return 0;
}

3.方法三:使用using将命名空间中的某个成员引入

命名空间域std被包含在头文件 iostream 中,同时cout 与 endl 被封装在命名空间域std中

cpp 复制代码
#include <iostream>

using std::cout;
using std::endl;

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

**补充:**命名空间域可以重名,编译器会将重名的两个命名空间域合并

四、命名空间域的嵌套使用

可以在命名空间域中嵌套多个命名空间域

cpp 复制代码
#include <iostream>

using std::cout;
using std::endl;
namespace bit
{
	namespace zz
	{
		int x = 0;
	}

	namespace zbc
	{
		int x = 10;
	}
}
int main()
{
	cout << bit::zbc::x << endl;
	cout << bit::zz::x << endl;

	return 0;
}

五、命名空间域展开与头文件展开的区别

头文件展开是将头文件中包含的内容拷贝到源文件中

命名空间域展开是扩大编译器的搜索范围,编译器可以到被展开的命名空间域中搜索变量、函数等

相关推荐
Algo-hx6 分钟前
C++编程基础(九):预处理指令
c++
凌康ACG7 小时前
Sciter之c++与前端交互(五)
c++·sciter
郝学胜-神的一滴9 小时前
Linux命名管道:创建与原理详解
linux·运维·服务器·开发语言·c++·程序人生·个人开发
晚风(●•σ )9 小时前
C++语言程序设计——11 C语言风格输入/输出函数
c语言·开发语言·c++
恒者走天下11 小时前
秋招落定,拿到满意的offer,怎么提高自己实际的开发能力,更好的融入团队
c++
天若有情67311 小时前
【c++】手撸C++ Promise:从零实现通用异步回调组件,支持链式调用+异常安全
开发语言·前端·javascript·c++·promise
学困昇11 小时前
C++中的异常
android·java·c++
合作小小程序员小小店12 小时前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全
Codeking__12 小时前
C++ 11 atomic 原子性操作
开发语言·c++
crescent_悦12 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法