- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
名称空间Namespace与转换函数与其他主题
1997/5/27 第十三章 名稱空間(Namespace) 與 轉換函數與其他主題 Namespace 關鍵字, 它會將所定義的名稱區域化, 只有在該區域時方能看到在該區域中所定義的名稱, 因此其許可同樣的名稱在不同區域中並存. Namespace的宣告 Namespace name{ // declarations } Ex: namespace Mynamespace{ int i,k; void myfunc(int j) {coutj;} class myclass { public: void seti(int x) { i=x;} int geti() { return i;} }; } Namespace的使用 在名稱空間中所宣告的識別字在該名稱 空間內可以直接被使用. 例如MyNamespace 中的return i即是直接使用變數I. 但若您是在名稱空間外要使用該名稱空間所定義的識別字時, 您便需使用作用範圍運算子(scope operator) 以指定您所要使用的名稱空間為何. MyNamespace::I =10; Namespace的使用 若在程式中常要使用到某一名稱空間的成員時, 若每次要存取該成員時便需指定名稱空間及作用圍範運算子, 然後才跟著所所要使用的成員, 如此便顯得非常麻煩. 因此using敘述便是用來減輕此一負擔, using敘述有以下兩種形式: using namespace name; using name::member; Namespace的使用 Ex:namespace firstNs{ class demo{ int I; public: demo(int x){I=x;} void seti(int I) {I=x;} int geti() {return I;} }; char str[]=“Illustrating namespace\n” int counter; } Int main() { using namespace firstNs;//方法一 for(counter=10;counter;counter--) coutcounter“”; using firstNs::str; //方法二 coutstr; } Namespace的使用 #includeiostream using namespace std; namespace Demo{ int a; } int x; namespace Demo{ int b; } int main() { using namespace Demo; a=b=x=100; couta“”b“”x; return 0; } 練習改寫成不需使用using namespace std敘述 #includeiostream #includefstream using namespace std; int main(int agrc,char *argv[]) { if(argc!=3){ cout“Usage Convert input output\n”; return 1; } ifstream fin(argv[1]);//open input file ofstream fout(argv[2]);//create output file if(!fout){ cout“Cannot open output file\n”; return 1; } if(!fin){ cout“Cannot open input file\n”; return 1; } char ch; fin.unsetf(ios::skipws); while(!fin.eof()){ finch; if(ch==‘ ’) ch= ‘|’; if(!fin.eof()){ foutch;} } fin.close(); fout.close(); return 0; } 建立轉換函數 轉換函數將一物件的值轉換成另一與其相容之資料型態 宣告:
文档评论(0)