c++命名空间,报错errlink1120的原因,using声明和using编译指令

using 命名空间

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <sstream>

using namespace std;
//命名空间
namespace A {//A是空间名
	int a;
	int f = 100;
	void func();
	namespace B {
		int b = 40;
	}
}
namespace N{
	int c=30;
	void func();
}
//注意6描述的,不加命名空间会导致链接错误   errlink  1120
void A::func() {
	cout << "A::f" << endl;
}
//给命名空间取别名
void test01() {
	namespace  newA = A;
	cout << newA::a << endl;
}

//类似 static int e=10;
namespace {
	int e = 10;
}
/*命名空间的注意
	注意1:命名空间只能卸载全局
	注意2:命名空间可以嵌套命名空间
	注意3:明明空间是开放的,可以在后期随时添加添加,新成员只能在加入后使用
	注意4:可以有没有名字的命名空间
	注意5;给命名空间取别名
	注意6:分文件编写时候,如果.h中有两个命名空间,但是在里面成员函数或成员变量重名的同时,在.cpp实现函数时要加上对应的的命名空间
	*/
int mya = 10;//全局常量区
int main()
{
	int mya = 20;//栈区
	cout << "mya=" << mya << endl;//打印的时候遵循就近远侧
	cout << "::mya=" <<:: mya << endl;//::表示访问全局变量
	cout <<"f="<<A::f<< endl;//表示访问明明空间内的变量   相当于是全局变量,不过被限制在namespace A中
	cout << "b="<<A::B::b << endl;//访问嵌套空间,一层层访问
	cout << "-------------" << endl;
	A::func();
	cout << "-------------" << endl;
	cout <<"e="<< e << endl;
	test01();
	system("pause");
	return 0;
}

using声明和编译指令

using namespace std;
namespace A
{
	int a = 10;
	int b = 20;
	int c = 40;
}
//using声明  命名空间内某个变量可以直接使用

void test01() {
	cout << A::a << endl;
	using A::a;//改行后a可以直接使用,但在此之后不能定义同名变量a,因为这里相当于把a直接拿过来了
	cout << a << endl;
}
//using编译指令    使得命名空间内的变量可以直接使用
void test02() {
	using namespace A;//直接使用A内变量,但是这里可以定义同名变量a
	//对比24行为啥不会报错 
	cout << a << endl;
	cout << b << endl;
	int a = 100;//这里int a为普通变量
}


int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值