C++ 命名空間詳解
一、C++ 命名空間
命名空間為了大型項(xiàng)目開發(fā),而引入的一種避免命名沖突的一種機(jī)制。比如說,在一個(gè)大型項(xiàng)目中,要用到多家軟件開發(fā)商提供的類庫(kù)。在事先沒有約定的情況下,兩套類庫(kù)可能在存在同名的函數(shù)或是全局變量而產(chǎn)生沖突。項(xiàng)目越大,用到的類庫(kù)越多,開發(fā)人員越多,這種沖突就會(huì)越明顯。
1.默認(rèn)NameSpace(Global&Function)
Global scope 是一個(gè)程序中最大的 scope。也是引起命名沖突的根源。C 語言沒有從語言層面提供這種機(jī)制來解決。也算是 C 語言的硬傷了。Global scope 是無名的命名空間。
//c 語言中如何訪問被局部變量覆蓋的全局變量
int val = 200;
int main()
{
int *p = &val;
int val = 100;
printf("func val = %d\n",val);
printf("global val = %d\n",*p);
return 0;
}
#include <iostream>
#include <string.h>
using namespace std;
int val = 200;
void func()
{
return ;
}
int main()
{
int val = 100;
cout<<"func val = "<<val<<endl;
cout<<"global val = "<<::val<<endl;
::func(); //因?yàn)椴荒茉诤瘮?shù)內(nèi)定義函數(shù)。所以前而的::沒有意義。
return 0;
}

2.語法規(guī)則
NameSpace是對(duì)全局(Global scope)區(qū)域的再次劃分。
1.聲明
命令空間的聲明及namespace中可以包含的內(nèi)容
namespace NAMESPACE
{
全局變量 int a;
數(shù)據(jù)類型 struct Stu{};
函數(shù) void func();
其它命名空間 namespace
}
2.使用方法
1.直接指定 命名空間: Space::a = 5;
2.使用 using+命名空間+空間元素:using Space::a;
3.使用 using +namespace+命名空間: using namespace Space;
3.支持嵌套
#include <iostream>
using namespace std;
namespace MySpace
{
int x = 1;
int y = 2;
namespace Other {
int m = 3;
int n = 4;
}
}
int main()
{
using namespace MySpace::Other;
cout<<m<<n<<endl;
return 0;
}
4.協(xié)作開發(fā)
同名命名空間自動(dòng)合并,對(duì)于一個(gè)命名空間中的類,要包含聲明和實(shí)現(xiàn)。
a.h
#ifndef A_H
#define A_H
namespace XX {
class A
{
public:
A();
~A();
};
}
#endif // A_H
a.cpp
#include "a.h"
using namespace XXX
{
A::A()
{
}
A::~A()
{
}
}
b.h
#ifndef B_H
#define B_H
namespace XX
{
class B
{
public:
B();
~B();
};
}
#endif // B_
b.cpp
#include "b.h"
namespace XX {
B::B()
{
}
B::~B()
{
}
}
main.cpp
include <iostream>
#include "a.h"
#include "b.h"
using namespace std;
using namespace XX;
int main()
{
A a;
B b;
return 0;
}
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
c++ 獲取數(shù)字字符串的子串?dāng)?shù)值性能示例分析
這篇文章主要為大家介紹了c++ 獲取數(shù)字字符串的子串?dāng)?shù)值示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
C語言圍圈報(bào)數(shù)題目代碼實(shí)現(xiàn)
大家好,本篇文章主要講的是C語言圍圈報(bào)數(shù)題目代碼實(shí)現(xiàn),感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01
深入分析C語言中結(jié)構(gòu)體指針的定義與引用詳解
本篇文章是對(duì)C語言中結(jié)構(gòu)體指針的定義與引用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

