命名空間

這裏寫圖片描述

爲什麼需要命名空間?

引入命名空間,用來處理程序中常見的同名衝突

什麼是命名空間?

  • 一個由程序設計者命名的內存區域
  • 根據需要指定一些有名字(或無名)的空間區域,將一些全局實體放在裏面,與其他全局實體分隔開

創建命名空間

//有名的命名空間
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;
}

運行結果:
這裏寫圖片描述

發佈了66 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章