049-C++中名字空间

#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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值