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; //产生二义性
}