命名空間 附加信息來區(qū)分不同庫中相同名稱的函數(shù)牌借、類了赌、變量等。使用了命名空間即定義了上下文吏夯。本質(zhì)上此蜈,命名空間就是定義了一個范圍。
定義命名空間
命名空間的定義使用關(guān)鍵字 namespace
噪生,后跟命名空間的名稱裆赵。
opencv 的命名空間(部分)
namespace cv
{
static inline uchar abs(uchar a) { return a; }
static inline ushort abs(ushort a) { return a; }
static inline unsigned abs(unsigned a) { return a; }
static inline uint64 abs(uint64 a) { return a; }
using std::min;
using std::max;
using std::abs;
using std::swap;
using std::sqrt;
using std::exp;
using std::pow;
using std::log;
}
為了調(diào)用帶有命名空間的函數(shù)或變量,需要在前面加上命名空間的名稱跺嗽,如下所示:
cv::boxFilter();
菜鳥教程實例
#include <iostream>
using namespace std;
// 第一個命名空間
namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}
// 第二個命名空間
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
int main () {
// 調(diào)用第一個命名空間中的函數(shù)
first_space::func();
// 調(diào)用第二個命名空間中的函數(shù)
second_space::func();
return 0;
}
輸出
Inside first_space
Inside second_space
using 指令
使用
using namespace
指令战授,這樣在使用命名空間時就可以不用在前面加上命名空間的名稱,該指令會告訴編譯器桨嫁,后續(xù)代碼將使用指定命名空間中的名稱植兰。
嵌套的命名空間
命名空間可以嵌套,您可以在一個命名空間中定義另一個命名空間璃吧,如下所示:
namespace namespace_name1 {
// 代碼聲明
namespace namespace_name2 {
// 代碼聲明
}
}
通過使用 ::
運算符來訪問嵌套的命名空間中的成員:
// 訪問 namespace_name2 中的成員
using namespace namespace_name1::namespace_name2;
// 訪問 namespace:name1 中的成員
using namespace namespace_name1;
實例
#include <iostream>
using namespace std;
// 第一個命名空間
namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}
// 第二個命名空間
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
}
using namespace first_space::second_space;
int main () {
// 調(diào)用第二個命名空間中的函數(shù)
func();
return 0;
}
輸出
Inside second_space