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;
}

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

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

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

相关推荐
不会代码的小猴5 小时前
21. 泛型编程上
开发语言·c++·笔记·算法
青瓦梦滋5 小时前
传输层UDP/TCP协议
linux·网络·c++·网络协议·tcp/ip·udp
一只旭宝6 小时前
细讲C加加【9】C++ std::function与std::bind详解|仿函数、绑定器、类成员绑定、占位符、成员偏移指针
开发语言·c++·算法
Lhan.zzZ8 小时前
在 Visual Studio 2022 中打造可扩展的动态链接库模块:从零搭建到原理解析
开发语言·c++·visual studio
zh路西法10 小时前
【3D SLAM源码解读系列】(二)Small_gicp——5 个积木搭出最优点云配准
c++·pcl·icp·fastgicp·smallgicp·gicp
fpcc11 小时前
ubuntu26环境下的开发环境安装处理
c++·并行编程
charlie11451419113 小时前
Cinux · 第一次跳进 Ring 3:用户态与特权隔离
开发语言·c++·操作系统·开源项目
别动我齐刘海13 小时前
机器学习基础2——C++、OpenCV、点云、Open3D
c++·人工智能·opencv·机器学习·计算机视觉·机器人·ros2
躺不平的理查德13 小时前
Windows C++ 第三方库使用流程备忘录--OpenCV
开发语言·c++
余额瞒着我当琳14 小时前
C++STL容器string--迭代器,string的接口,string的遍历,访问方式
c++