C++的命名空间域

一、域作用限定符

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

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

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

三、命名空间域

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

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

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

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

#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.方法二: 命名空间域展开(展开后就无需使用域作用限定符来指定变量的位置)

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

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

相关推荐

  1. 关于c++命名空间

    2024-01-19 07:02:02       15 阅读
  2. std命名空间C++标准库命名空间

    2024-01-19 07:02:02       16 阅读
  3. c++ 命名空间 匿名命名空间

    2024-01-19 07:02:02       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-19 07:02:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-19 07:02:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-19 07:02:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-19 07:02:02       20 阅读

热门阅读

  1. C++写csv文件

    2024-01-19 07:02:02       33 阅读
  2. Unity文字游戏开发日志(1)—— 打字机效果

    2024-01-19 07:02:02       35 阅读
  3. Mysql核心知识命令汇总

    2024-01-19 07:02:02       35 阅读
  4. bevy the book 20140118翻译(全)

    2024-01-19 07:02:02       30 阅读
  5. 【中断之GPT问答】

    2024-01-19 07:02:02       28 阅读
  6. Oracle中的索引

    2024-01-19 07:02:02       30 阅读
  7. Django笔记(四):视图views

    2024-01-19 07:02:02       34 阅读
  8. Linux 使用PS命令掌握进程管理

    2024-01-19 07:02:02       37 阅读
  9. jmeter的使用教程

    2024-01-19 07:02:02       32 阅读
  10. Spring 核心之 IOC 容器学习二

    2024-01-19 07:02:02       25 阅读
  11. 自定义Dubbo RPC通信协议

    2024-01-19 07:02:02       20 阅读