命名空间

这里写图片描述

为什么需要命名空间?

引入命名空间,用来处理程序中常见的同名冲突

什么是命名空间?
  • 一个由程序设计者命名的内存区域
  • 根据需要指定一些有名字(或无名)的空间区域,将一些全局实体放在里面,与其他全局实体分隔开
创建命名空间
//有名的命名空间
namespace ns//-->空间名
{
    //函数、类、结构体、模板、变量、常量
}
//无名的命名空间
namespace
{
    //函数、类、结构体、模板、变量、常量
}
//命名空间的嵌套
namespace ns1
{
    namespace ns2
    {}
}
命名空间成员的访问方法
  • 命名空间名::命名空间成员名
namespace ns
{
    int a = 1;
}
cout<<ns::a<<endl;
  • 使用命名空间别名
namespace ns
{
    int a = 1;
}
namespace NS = ns;
cout<<NS::a<<endl;
  • 使用“using 命名空间名::命名空间成员名“
namespace ns
{
    int a = 1;
}
using ns::a;
cout<<a<<endl;
  • 使用“using 命名空间名”
namespace ns
{
    int a = 1;
}
using ns;
cout<<a<<endl;
无名的命名空间

因为命名空间没有名字,所以在其他的文件中显然无法使用,它只在本文件的作用域内有效

namespace 
{
    void fun()//该函数只能在这个命名空间使用
    {
        cout<<"namespace fun()"<<endl;
    }
}

static void fun()//该函数也只能在本文件中使用,出了作用域就无法使用
{
    cout<<"static fun()"<<endl;
}
标准命名空间–std
//常用的方式
include<iostream>
using namespace std;  // std
//也可以和其他命名空间一样使用
std::cout<<"嘿嘿"<<endl;
使用命名空间解决同名冲突
header1.h

#include<string>
#include<cmath>
using namespace std;
namespace ns1
{
    class student
    {
    public:
        student(int num, string name, char sex)
        {
            _num = num;
            _name = name;
            _sex = sex;
        }
        void get_stuinfo()
        {
            cout << _num << " " << _name << " " << _sex << endl;
        }
    private:
        int _num;
        string _name;
        char _sex;
    };
    double fun(double a, double b)
    {
        return sqrt(a + b);
    }
}
header2.h

#include<string>
#include<cmath>
using namespace std;
namespace ns2
{
    class student
    {
    public:
        student(int num, string name, char sex)
        {
            _num = num;
            _name = name;
            _sex = sex;
        }
        void get_stuinfo()
        {
            cout << _num << " " << _name << " " << _sex << endl;
        }
    private:
        int _num;
        string _name;
        char _sex;
    };
    double fun(double a, double b)
    {
        return sqrt(a - b);
    }
}
main.cpp

#include<iostream>
#include"header1.h"
#include"header2.h"

int main()
{
    ns1::student s1(11,"wgb",1);
    s1.get_stuinfo();
    ns2::student s2(22,"bgw",2);
    s2.get_stuinfo();
    cout << ns1::fun(2,1) << endl;
    cout << ns2::fun(2, 1) << endl;
    return 0;
}

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值