1、用途:解决名称冲突’。
2、在命名空间下可以存放函数、变量、结构体、类等。
3、声明:命名空间必须声明在全局作用域下。
4、命名空间是可以嵌套命名空间的。
5、我们可以随时向命名空间添加成员,命名空间是开放的。
6、命名空间可以写成匿名的。
7、可以给一个命名空间起别名。
#include<iostream>
using namespace std;
class MyHome
{
public:
void eat()
{
cout<<"在家吃饭"<<endl;
}
}
class MySchool
{
public:
void eat()
{
cout<<"在学校吃饭"<<endl;
}
}
void test_01() //解决名称冲突
{
MyHome::eat();
MySchool::eat();
}
namespace M_A //在命名空间下可以存放函数、变量、结构体、类等
{
char a;
void test_02_01(){};
struct Dog{};
class People{};
}
void test_02()
{
//namespace animal{}; //不可以将命名空间写在局部范围内
}
//命名空间是可以嵌套命名空间
namespace M_C
{
int cou=12;
namespace M_B
{
double row=100;
}
}
//可以随时向命名空间添加成员
namespace M_C
{
int age=24;
}
void test_03()
{
cout<<"cou = "<<M_C::cou<<endl;
cout<<"age = "<<M_C::age<<endl;
}
//命名空间可以写成匿名的
namespace
{
int anonymity=100;
int price=99;
}
void test_04()
{
cout<<"anonymity = "<<::anonymity<<endl;
cout<<"price = "<<price<<endl;
}
//可以给一个命名空间起别名
namespace MyOldFriendsAge
{
int friAge=30;
}
void test_05()
{
namespace M_Age=MyOldFriendsAge; //起别名
cout<<"friAge = "<<M_Age::friAge<<endl;
cout<<"friAge = "<<MyOldFriendsAge::friAge<<endl;
}
int main()
{
//test_01();
//test_02();
//test_03();
//test_04();
test_05();
system("pause");
return 0;
}