c++ namespace

命名空间

C语言没办法解决类似这样的命名冲突问题,所以C++提出了namespace来解决

#include <stdio.h>
#include <stdlib.h>
int rand = 10;
// C语言没办法解决类似这样的命名冲突问题,所以C++提出了namespace来解决
int main()
{
 printf("%d\n", rand);
 return 0;
}
// 编译后后报错:error C2365: “rand”: 重定义;以前的定义是“函数”

命名空间使用

一个命名空间就定义了一个新的作用域,命名空间中的所有内容都局限于该命名空间中

更多的域

类域
命名空间域
局部域
全局域

在这里插入图片描述

局部域优先全局域

展开了命名空间,编译时就会去所展开的命名空间寻找
这里是全局域和命名空间域的同名变量发生冲突

在这里插入图片描述

所以可以指定展开空间域
在这里插入图片描述

命名空间可以嵌套

// 命名空间可以嵌套
// test.cpp
namespace N1
{
 int a;
 int b;
 int Add(int left, int right)
 {
 return left + right;
 }
 namespace N2
 {
 int c;
 int d;
 int Sub(int left, int right)
 {
 return left - right;
 }
 }
}

在这里插入图片描述

同一个工程中允许存在多个相同名称的命名空间,编译器最后会合成同一个命名空间中。
// ps:一个工程中的test.h和上面test.cpp中两个N1会被合并成一个

工程中使用展开 和 日常使用展开常用的

日常使用练习 随意展开

在这里插入图片描述

工程中指定展开

std::cout << "hello world" << std::endl;

展开常用的

// 展开某个:把常用展开
using std::cout;
using std::endl;
int main()
{
	int x = 10;
	// << 流插入运算符
	cout << "hello world" << x << '\n' << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;
	cout << "hello world" << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值