#include <iostream>
using namespace std;
/**
假设这样一种情况,当一个班上有两个名叫 Zara 的学生时,为了明确区分它们,我们在使用名字之外,不得不使用一些额外的信息,
比如他们的家庭住址,或者他们父母的名字等等。同样的情况也出现在 C++ 应用程序中。例如,您可能会写一个名为 xyz() 的函数,
在另一个可用的库中也存在一个相同的函数 xyz()。这样,编译器就无法判断您所使用的是哪一个 xyz() 函数。因此,引入了命名空
间这个概念,专门用于解决上面的问题,它可作为附加信息来区分不同库中相同名称的函数、类、变量等。使用了命名空间即定义了上下文。
本质上,命名空间就是定义了一个范围。
*/
//第一个命名空间
namespace first_space {
int age = 10;
char* color = "red";
void func(){
cout<<"Inside first_space"<<endl;
}
class Student {
public:
char* name;
int score;
public:
void showInfo(){
cout<<"FirstSpace Name is "<<name<<" score is "<<score<<endl;
}
};
}
//第二个命名空间
namespace second_space {
int age = 12;
char* color = "blue";
void func(){
cout<<"Inside second_space"<<endl;
}
class Student {
public:
char* name;
int score;
public:
void showInfo(){
cout<<"SecondSpace Name is "<<name<<" score is "<<score<<endl;
}
};
}
int main(int argc, char const *argv[])
{
/* code */
// 调用第一个命名空间中的函数
first_space::func();
// 调用第二个命名空间中的函数
second_space::func();
cout<<"First Space: age "<<first_space::age<<" color "<<first_space::color<<endl;
cout<<"Second Space: age "<<second_space::age<<" color "<<second_space::color<<endl;
first_space::Student* student1 = new first_space::Student;
student1->name = "lisi";
student1->score = 89;
student1->showInfo();
second_space::Student* student2 = new second_space::Student;
student2->name = "wangwu";
student2->score = 91;
student2->showInfo();
return 0;
}
输出如下:
Inside first_space
Inside second_space
First Space: age 10 color red
Second Space: age 12 color blue
FirstSpace Name is lisi score is 89
SecondSpace Name is wangwu score is 91