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

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

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

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

相关推荐
General_G13 小时前
创建型模式—原型(Prototype)模式
c++·设计模式·原型模式
syagain_zsx13 小时前
protobuf 实战:从 .proto 到 C++ 序列化的完整链路
c++·学习·程序人生·谷歌·protobuf
welfare96214 小时前
新号别搞:C++_list
开发语言·c++
xiaoye-duck14 小时前
《C++ 项目:手写大模型接入 SDK》云端 API 调用基础与 Apifox 调试实战
网络·c++·语言模型
坤坤子吖14 小时前
Linux 线程同步与互斥——条件变量与线程同步
linux·开发语言·c++·笔记·学习
杜 硕14 小时前
从零开始的C++生活——第二讲——03
c++·生活
布莱克60515 小时前
QtWidgets 与 QML:两大 UI 开发框架的全面对比
开发语言·c++·qt·ui·架构
hetao173383715 小时前
2026-10-20 hetao1733837 的刷题记录
c++·算法
x10n917 小时前
微软 VC++ 运行库合集VCRedistPack
开发语言·c++·microsoft·vc++运行库·dll报错
qz_Serene17 小时前
C++:string(底层,常用接口,具体题目,模拟实现)
开发语言·c++