c++ 命名空间 namespace (通俗易懂)

###c++ 命名空间 namespace :

假设如果班级里有两个名字为 `小明` 的同学,为了区分他们 我们可能会在身高 长相 发型 等等其他条件判断谁是谁

编译器也是这样 当你写了 两个 函数名字一样的函数 编译器不知道引用哪一个

因此,引入了命名空间这个概念,专门用于解决上面的问题,它可作为附加信息来区分不同库中相同名称的函数、类、变量

等。使用了命名空间即定义了上下文。本质上,命名空间就是定义了一个范围 

####定义命名空间:

namesoace xxx{
	//code
}
用关键字 namespace 

demo:

#include <iostream>

namespace first_space {
	//相同的函数名字 不同的命名空间
	void fun_() {
		std::cout << "this is first_space" << std::endl;
	}
}

namespace second_space {

	void fun_() {
		std::cout << "this is second_space" << std::endl;
	}
}

int main()
{
	//命名空间1
	first_space::fun_();

	//命名空间2
	second_space::fun_();

	system("pause");

    return 0;
}



这里写图片描述

using 指令

您可以使用 using namespace 指令,这样在使用命名空间时就可以不用在前面加上命名空间的名称。
这个指令会告诉编译器,后续的代码将使用指定的命名空间中的名称
#include <iostream>

namespace first_space {

	void fun_() {
		std::cout << "this is first_space" << std::endl;
	}
}

namespace second_space {

	void fun_() {
		std::cout << "this is second_space" << std::endl;
	}
}

using namespace first_space; //使用命名空间1

int main()
{

	fun_();

	system("pause");

    return 0;
}

这里写图片描述

using 指令也可以用来指定命名空间中的特定项目。例如,如果您只打算使用 std 命名空间中的 cout 部分.

using std::cout;
using std::cout;//指定命名空间中的特定项目


int main()
{

	//cout 可以不加 命名空间,endl 还是需要加
	cout << "Hello namespace!" << std::endl;

	system("pause");

    return 0;
}

这里写图片描述

###嵌套的命名空间:

namespace xxx{
	//code
	namespace xxx{
		//code
	}
}

demo:

#include <iostream>

//嵌套的命名空间
namespace first_space {

	void fun_() {
		std::cout << "this is first_space" << std::endl;
	}

	namespace second_space {

		void fun_() {
			std::cout << "this is second_space" << std::endl;
		}
	}
}

int main()
{
	//命名空间1
	first_space::fun_();

	//命名空间2
	first_space::second_space::fun_();
	
	system("pause");

    return 0;
}

这里写图片描述

也可以用 using 指令 using namespace first_space::second_space;

using namespace first_space::second_space;


int main()
{
	fun_();

	system("pause");

    return 0;
}

这里写图片描述

	98年菜鸟一枚,请大佬们多多关照!
  • 16
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值