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