命名空間是為了應(yīng)對命名沖突這種情況的出現(xiàn)而產(chǎn)生的 .命名空間是可擴(kuò)展的.你可以使用相同的命名空間來定義你的那些在物理上處于不同位置的組件.一個典型的例子就是namespace std.
你可以有三種選擇來使用std命名空間.
1.使用std::作為前綴.
如:
std::cout << std::hex << 3.4 << std::endl;
2.使用using 進(jìn)行預(yù)定義
using std::cout;
using std::endl;
然后這樣使用:
cout << std::hex << 3.4 << endl;
3.直接使用using.
using namespace std;
cout << hex << 3.4 << endl;
不要在代碼上下文不明確的地方使用這種用法( 如頭文件中).
c++標(biāo)準(zhǔn)中對于
頭文件引入使用了一種新的寫法,如:
#include <iostream>
這實(shí)際上是引入了c++的標(biāo)準(zhǔn)模板庫的iostream.h文件.
而對于舊的c語言的頭文件,可以使用這種方式引入:
#include <cstdlib> //相當(dāng)于<stdlib.h>
#include <cstring> //相當(dāng)于<string.h>
有意思的是,如果在引入頭文件的時候這樣寫,可以把c風(fēng)格的函數(shù)加上std命名空間來使用.
如:
#include <cstring>
#include<cstdio>
int main()
{
std::printf("%d",std::strlen("hello world!"));
}
當(dāng)然,仍然可采用兼容于c風(fēng)格的頭文件引入方式:
#include <stdlib.h>
posted on 2007-06-25 21:18
littlegai 閱讀(111)
評論(0) 編輯 收藏 引用 所屬分類:
我的讀書筆記