C++ namespace

namespace

假设一个项目中有两个模块中有相同的函数,则需要用命名空间来区分

spacex

头文件:

#include <iostream>
using namespace std;
namespace spacex
{
	void test();
}

源文件

#include "spacex.h"

void spacex::test()
{
	cout << "spacex" << endl;
}

spacey

头文件

#include <iostream>
using namespace std;

namespace spacey
{
	void test();
}

源文件

#include <iostream>
using namespace std;

namespace spacey
{
	void test();
}

主函数文件

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include "spacex.h"
#include "spacey.h"
using namespace std;


//namespace命名空间主要用途 用来解决命名冲突的问题
void test()
{
	spacex::test();
	spacey::test();
}


int main() {
	test();
	system("pause");
	return EXIT_SUCCESS;
}

命名空间:
1、命名空间下 可以放函数、变量、结构体、类
2、命名空间必须定义在全局作用域下
3、命名空间可以嵌套命名空间
4、命名空间是开放的,可以随时往原先的命名空间添加内容(再写一个命名空间不是覆盖,而是添加)
5、当写了无名命名空间,相当于写了 static ; static
6、最好不要再头文件中写命名空间,因为会展开到应用了该头文件的模块中,容易出错

using

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

namespace spacex
{
	int id = 10;
}
void test01()
{
	int id = 20;
	//using 声明  注意歧义的问题
	//写了using声明后  下面这行代码说明以后看到的id 是用spacex下的
	//但是  编译器又有就近原则
	//using spacex::id;  //这里直接使用了命名空间里的某个值
	cout << id << endl;
}
//using编译指令
namespace spacey
{
	int id = 30;
}
void test02()
{
	//int id = 20;
	//using编译指令
	using namespace spacex; //打开spacex房间
	using namespace spacey;//打开spacey房间
	//打开了多个房间也会引起歧义
	cout << spacey::id << endl;
}


int main() {
	//test01();
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

::运算符

::是作用域运算符,
std::指使用std的命名空间下的作用域
::指全局作用域

#define _CRT_SECURE_NO_WARNINGS//strcpy等函数vs不建议,而需要使用strcpy_s,如果想使用strcpy则需要加这个声明
#include <iostream>
using namespace std;
int a = 200;
void test()
{
	int a = 100;
	cout << "局部变量 : " << a << endl;
	//双冒号 作用域运算符  ::全局作用域
	cout << "全局变量 : " << ::a << endl;
}
int main() {
	test();
	system("pause");
	return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值