[C++对C语言的扩展一]

1.作用域运算符"::"

表明数据,函数的归属性。

#include <iostream>

using namespace std;

int a = 10;

void test01()
{
	int a = 20;
	cout << "全局变量a=" << ::a << endl;
	cout << "局部变量a=" << a << endl;
}

int main()
{
	
	test01();
	return 0;
}

运行结果:

2.使用命名空间(namespace)解决命名冲突

        创建名字是程序设计中最基本的活动,当一个项目很大时,不可避免的包含大量名字,在C语言中可以通过static关键字来使得名字只得在本编译单元内可用,在C++中通过一种命名空间来控制对名字的访问。

        在C++中,名字(name)可以是符号常量、变量、函数、结构、枚举、类和对象等等。在大规模程序设计,以及程序员在使用各种各样的C++库时,名称互相冲突的可能性很大,为了避免这种情况,标准C++引用关键字namespac(命名空间),可以很好的控制表示分的作用域。

2.1 namespace命名空间的定义

namespace A
{
	int a = 10;
}
namespace B
{
	int a = 20;
}

void test01()
{
	
	cout << "A中的a=" << A::a << endl;
	cout << "B中的a=" <<B::a << endl;
}

2.2 命名空间只能在全局范围内定义

局部定义命名空间是错误的。

void test01()            //错误示范
{
	namespace A
	{
		int a = 10;
	}
	namespace B
	{
		int a = 20;
	}
	cout << "A中的a=" << A::a << endl;
	cout << "B中的a=" <<B::a << endl;
}

2.3 命名空间可以嵌套定义

namespace A
{
	int a = 10;
		namespace B
	{
		int a = 20;
	}
}

void test01()
{

	cout << "A中的a=" << A::a << endl;
	cout << "B中的a=" <<A::B::a << endl;
}

2.4 命名空间是开放的,可以随时添加新成员

namespace A
{
	int a = 10;
}
namespace A
{
	int b = 20;
}

void test01()
{

	cout << "A中的a=" << A::a << endl;
	cout << "A中的b=" <<A::b << endl;
}

2.5 命名空间可以存放变量和函数

namespace A
{
	int a = 10;
	void fun()
	{
		cout << a+a << endl;
	}
}

void test01()
{

	cout << "A中的a=" << A::a << endl;
	A::fun();
}

也可在“命名空间外部”定义

namespace A
{
	int a = 10;
	void fun();
}

void A::fun()
{
	cout << a + a << endl;
}
void test01()
{

	cout << "A中的a=" << A::a << endl;
	A::fun();
}

2.6 无名的命名空间,意味着命名空间内的内容只能在本文件中访问

namespace 
{
	int a = 10;
	void fun()
	{
		cout << a + a << endl;
	}
}

void test01()
{
	cout << a << endl;
	fun();
}

2.7 命名空间的名字可以有多个

namespace longName
{
	int a = 10;
	void fun()
	{
		cout << a + a << endl;
	}
}

void test01()
{
	namespace shortName = longName;
	cout << shortName::a << endl;
	shortName::fun();
}

2.8 using命名空间

using编译指令使得整个命名空间标识符可用

namespace A
{
	int a = 10;
	void fun()
	{
		cout << a + a << endl;
	}
}
namespace B
{
	int a = 20;
}

void test01()
{
	using namespace A;      //不会产生二义性
	cout << a << endl;
	int a = 20;
	fun();
}
void test02()
{
	using namespace A;
	using namespace B;
	cout << a << endl;   //产生二义性
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值