命名空间

命名空间的使用

#include<iostream>
#include<cstdlib>
using namespace std;

namespace string1
{
	char str[10]{ "calc" };
	void show()
	{
		//cout << "holle" << endl;
		cout << str << endl;
	}
}
namespace string2
{
	char str[10]{ "notepad" };
}

void main()
{
	//命名空间的函数与变量
	system(string1::str);//calc
	system(string2::str);//notepad
	string1::show();//holle

	cin.get();
}

命名空间的权限

#include<iostream>

using namespace std;

namespace data
{
	//private int num;//报错,命名空间不存在私有的概念
	int num;
	void show()
	{
		cout << num << endl;
	}
}
using namespace data;//使用命名空间
namespace dataX
{
	int num = 100;
	namespace run
	{
		int num = 10;
		void show()//命名空间里内层覆盖外层
		{
			//cout << ::num << endl;//直接访问全局变量,全局变量不存在就返回0
			cout << num << endl;
			cout << dataX::num << endl;//100
		}
	}
	
}
using namespace dataX;//使用命名空间必须在定义之后

void main1()
{
	//num = 10;//报错,num不明确,需要指明一下
	data::num = 10;//指明是data里的num
	show();

	cin.get();
}

void main()
{
	dataX::run::show();//10

	cin.get();
}

命名空间的意义

main.h

//int num = 20;//多重定义  外部全局变量冲突
//data命名空间的名称
namespace data
{
	int num = 20;//解决外部全局变量冲突
}
namespace.cpp

#include<iostream>
#include"main.h"

using namespace std;

int num = 10;

void main()
{
	cout << num << endl;//10
	cout << data::num << endl;//20

	cin.get();
}

std和别名

#include<iostream>

//using,可以省略std   std标准空间
//制定命名空间
//原则禁止using namespace std;//明确空间

//可以给自己定义的起别名,不推荐跟标准起别名
namespace bobo = std;//可以替换  别名的作用  自己创建的空间也可以
void main()
{
	std::cout << "holle";
	std::cin.get();
	bobo::cout << "holle";
	bobo::cin.get();
}

匿名命名空间

#include<iostream>
#include<cstdlib>

using namespace std;
//匿名命名空间相当于全局变量
namespace
{
	int x = 10;
}
//int x = 5;//报错

void main()
{
	
	cout << x << endl;//10

	cin.get();
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值