




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
ObjectOrientedConcept蔡文能交通大學(xué)資訊工程學(xué)系OOA,OOD,
OOP/~tsaiwn/oop/1AgendaReview:DataRepresentationinthecomputerWhyusingstruct?WhatisObject?Whatisclass?OOConcept?Whyusingclass?Howtobuildacomponent?OOfeaturesEncapsulation,InformationHiding,Inheritance,Polymorphism2電腦內(nèi)如何儲(chǔ)存資料?如何表示文字?ASCII?EBCDIC?…如何表示數(shù)值?整數(shù)?(char,short,int,long)longlong,boolean?實(shí)數(shù)?(float,double)數(shù)值的範(fàn)圍?實(shí)數(shù)數(shù)值的準(zhǔn)確度(precision)其它?問(wèn)題與思考(DataRepresentation)longlongisintroducedinC99boolisintroducedinC++3問(wèn)題與思考(如何表示文字?)#include<stdio.h>unsignedcharx[999]={0};main(){intm=0x41,n=97;x[0]=m;x[1]=n;x[2]=98;x[3]=99;x[7]=063;x[8]=0x38;/*063==51
*/x[4]='Y';x[5]='o';x[6]='u';printf("==%s==\n",x);}
4問(wèn)題與思考(如何表示文字?)ccbsd2:tsaiwn>gcctestc.cccbsd2:tsaiwn>./a.out==AabcYou38==ccbsd2:tsaiwn>先把前面程式存入testc.c編譯與連結(jié)執(zhí)行5問(wèn)題與思考(中文碼?)#include<stdio.h>unsignedcharx[9]={0};main(){intm=0xa4,n=0x6a;x[0]=m;x[1]=n;x[2]=0xae,x[3]=97;x[4]=0xa6,x[5]=0x6e;printf("==%s==\n",x);}
6問(wèn)題與思考(中文碼?)ccbsd2:tsaiwn>gcctestc.cccbsd2:tsaiwn>./a.out==大家好==ccbsd2:tsaiwn>先把前面程式存入testc.c編譯與連結(jié)執(zhí)行7實(shí)數(shù)與準(zhǔn)確度(precision)#include<stdio.h>floatx,xdelta;inti;/*precision.c*/main(){doubley;x=1234567.2,xdelta=0.0001;printf("Beforeloop,x=%f\n",x);for(i=1;i<=8000;i++){y=x+xdelta;/******/if(i==1)printf("firsty=%f\n",y);x=y;}printf("Afterloop,x=%f\n",x);}
8float實(shí)數(shù)準(zhǔn)確度七位多ccbsd2:precision/>gccprecision.cccbsd2:precision/>./a.outBeforeloop,x=1234567.250000firsty=1234567.250100Afterloop,x=1234567.250000ccbsd2:precision/>
float實(shí)數(shù)佔(zhàn)用32bits9double實(shí)數(shù)準(zhǔn)確度#include<stdio.h>doublex,xdelta;inti;/*precdbl.c*/main(){doubley;x=1234567.2,xdelta=0.0001;printf("Beforeloop,x=%f\n",x);for(i=1;i<=8000;i++){y=x+xdelta;/******/if(i==1)printf("firsty=%f\n",y);x=y;}printf("Afterloop,x=%f\n",x);}
10double實(shí)數(shù)準(zhǔn)確度十五位多ccbsd2:precision/>gccprecdbl.cccbsd2:precision/>./a.outBeforeloop,x=1234567.200000firsty=1234567.200100Afterloop,x=1234568.000001ccbsd2:precision/>
double實(shí)數(shù)佔(zhàn)用64bits11SummaryaboutDataRepresentation變數(shù)(variable)就是佔(zhàn)住記憶體一小塊地方有個(gè)名字變數(shù)名字要用字母開(kāi)頭變數(shù)的種類(類型):整數(shù):char,(byte),short,int,long,longlong(C99才有)實(shí)數(shù):float,double,longdouble數(shù)值的絕對(duì)值太大無(wú)法存入規(guī)定格式稱Overflow數(shù)值的絕對(duì)值太小無(wú)法存入規(guī)定格式被電腦當(dāng)作0存起來(lái)稱Underflow,實(shí)數(shù)才會(huì)!整數(shù)沒(méi)有underflowJava語(yǔ)言有8種primitivedatatypeboolean,byte,char,short,int,long,float,doublefloat的準(zhǔn)確度只有二進(jìn)位24位,約十進(jìn)位7位強(qiáng)double的準(zhǔn)確度只有二進(jìn)位53位,約十進(jìn)位15位強(qiáng)自訂型別(UserDefinedDataType)12整數(shù)overflow(溢位)#include<stdio.h>intmain(){shortans=32765;intk;for(k=1;k<=6;++k){printf("=%d\n",ans++);}}=32765=32766=32767=-32768=-32767=-32766物極必反?13float實(shí)數(shù)overflow(溢位)/*seeeeeeeefffffffgggggggghhhhhhhh*//*+/-1.fffffffgggggggghhhhhhhh*2**(eeeeeeee-127)*//*eeeeeeee:Exponentbase2excess127*/#include<stdio.h>#include<math.h>intmain(){floatans=pow(2,125);/*2的125次方*/intk;for(k=1;k<=6;++k){printf("=%f\n",ans);ans*=2.0;}}Inf=無(wú)窮大=Inf=Inf=Inf14float實(shí)數(shù)underflow(虧失)/*seeeeeeeefffffffgggggggghhhhhhhh*//*+/-1.fffffffgggggggghhhhhhhh*2**(eeeeeeee-127)*//*eeeeeeee:Exponentbase2excess127*/#include<stdio.h>#defineDLOOP146intmain(){intk;floatans=1.0;for(k=1;k<=DLOOP;++k)ans=ans/2.0;/*ans=pow(2,-146);*/for(k=1;k<=7;++k){printf("=%12.8g\n",ans);ans/=2.0;}return0;}=1.1210388e-44=5.6051939e-45=2.8025969e-45=1.4012985e-45=0=0=015再談變數(shù)Variable變變變變數(shù)當(dāng)然會(huì)變才叫變數(shù)–廢話!變數(shù)命名規(guī)則與慣例?averageScore,
n,x變數(shù)放在電腦的記憶體–何處?與程式一起,與程式分離?–由Linker負(fù)責(zé)堆疊區(qū)(STACK)?
嘿洗蝦密碗糕啊?變數(shù)的能見(jiàn)範(fàn)圍(Scope)?或說(shuō)有效範(fàn)圍函數(shù)(函式)內(nèi)的變數(shù):Localvariable局部(區(qū)域)變數(shù)函數(shù)外的變數(shù):Globalvariable整體變數(shù)變數(shù)何時(shí)生出?何時(shí)死掉?生命期
(Lifetime)?16變數(shù)分類依能見(jiàn)範(fàn)圍(Scope,或說(shuō)有效範(fàn)圍)?Local區(qū)域vs.Global整體依何時(shí)給它記憶體位置(稱作binding)Staticvariable:靜態(tài)變數(shù),Run之前(compile/Link)Dynamicvariable:動(dòng)態(tài)變數(shù),Run之後才會(huì)做binding(就是Run之後才給它位置)自動(dòng)要自動(dòng)還:auto變數(shù)(function內(nèi)沒(méi)寫(xiě)static)手動(dòng)要:使用malloc或calloc要,用free還(C++用new和delete)auto變數(shù)在stack堆疊手動(dòng)要的(malloc,calloc)在Heap堆積17變數(shù)(Variable)
的Scope,Lifetime變數(shù)的能見(jiàn)範(fàn)圍(Scope,或說(shuō)有效範(fàn)圍)函數(shù)(函式)內(nèi)的變數(shù):Localvariable局部(區(qū)域)變數(shù):只有在函數(shù)內(nèi)有效函數(shù)外的變數(shù):Globalvariable(整體變數(shù))Globalvariable:宣告之後就一直有效變數(shù)生命期(Lifetime)?靜態(tài)變數(shù)從程式開(kāi)始Run就“出生〞Auto變數(shù)在進(jìn)入函數(shù)時(shí)生出,離開(kāi)函數(shù)時(shí)死掉(把記憶體還給系統(tǒng))沒(méi)有宣告static的:Local變數(shù)就是Auto變數(shù)18Global變數(shù)vs.Local變數(shù)#include<iostream.h>intx=38,y=250;/*Global*/voidsub1(int);/*見(jiàn)後面程式*/intmain(){intx=49;/*Local*/sub1(::x);/*Global的x==38*/sub1(x);/*Local的x==49*/
cout<<"x="<<x<<endl;cout<<"outsidex="<<::x<<endl;cout<<"y="<<y<<endl;return0;/*0inmain()meansOK*/}19Global變數(shù)vs.Local變數(shù)voidsub1(inty){cout<<"y="<<y<<endl;x++;/*Global的x,因?yàn)長(zhǎng)ocal沒(méi)有x*/::x++;/*也是Global的x*/y++;/*因?yàn)閥是passbyvalue,回去不會(huì)變*/::y++;/*是Global的y*/return;/*不寫(xiě)也可以*/}(Cont)passbyvalue就是callbyvalue講法不同而已
20StaticLocal變數(shù)#include<iostream.h>intfa(){intx=1;
returnx++;/*先取其值,再做++*/}intfb(){
static
intx=1;/*注意staticintx=1;*/
returnx++;}intmain(){cout<<"fa()="<<fa()<<fa()<<fa()<<endl;cout<<"fb()="<<fb()<<fb()<<fb()<<endl;return0;/*0inmain()meansOK*/}returnx++;和return++x;不同!21StaticLocal變數(shù)intfa(){intx=1;returnx++;/*先取其值,再做++*/}intfb(){static//把static寫(xiě)在以下左方也一樣intx=1;//注意staticintx=1;returnx++;}(Cont)22StaticLocal變數(shù),evaluation順序#include<stdio.h>intfa();/*宣告*/intfb();intmain(){/*不同系統(tǒng)可能不同答案*/printf("fa()=%d%d%d\n", fa(),fa(),fa());printf("fb()=%d%d%d\n", fb(),fb(),fb());return0;/*0inmain()meansOK*/}//intfa()…也可以寫(xiě)在另一個(gè)檔案內(nèi)23Evaluation順序#include<stdio.h>intgg(intx){staticans=0;ans=x+ans*ans;returnans;}intmain(){/*不同系統(tǒng)可能不同答案!*/inthaha=gg(1)+gg(2)+gg(3);/*先做哪個(gè)gg()?*/printf("haha=%d\n",haha);return0;}
expression中有多個(gè)函數(shù)叫用會(huì)先做哪個(gè)gg()?C/C++沒(méi)有規(guī)定!所以看寫(xiě)compiler的人高興
24Auto變數(shù)不可佔(zhàn)太多memoryAuto變數(shù)就是沒(méi)寫(xiě)static的Local變數(shù)Auto變數(shù)是在進(jìn)入函數(shù)時(shí)才在STACK區(qū)安排記憶體,在離開(kāi)函數(shù)(return)時(shí)就還掉(改變StackPointer)STACK區(qū)一般不會(huì)很大(幾拾KBytes)Auto變數(shù)用STACK區(qū),所以太大的array不能用叫用函數(shù)時(shí),returnaddress也會(huì)被推入
STACK
參數(shù)傳遞也是用STACK區(qū)C/C++推入?yún)?shù)時(shí)是先推入最後一個(gè)參數(shù),這使得第一個(gè)參數(shù)會(huì)在堆疊的最上方,進(jìn)入函數(shù)時(shí),STACK中
returnaddress之下就是第一個(gè)參數(shù)C/C++離開(kāi)函數(shù)時(shí),函數(shù)不負(fù)責(zé)拿掉STACK中
的參數(shù),那是叫用函數(shù)那個(gè)程式的責(zé)任!(與其它語(yǔ)言不同)25Auto變數(shù)佔(zhàn)用STACK區(qū)memoryAuto變數(shù)就是沒(méi)寫(xiě)static的Local變數(shù)CPUIPSPInstructionPointerStackPointer系統(tǒng)區(qū)系統(tǒng)區(qū)程式+靜態(tài)dataHEAP堆積malloc(),new()STACK(參數(shù)與Auto變數(shù))Heap由上往下長(zhǎng)Stack由下往上長(zhǎng)26Static變數(shù)?Global變數(shù)都是static的變數(shù)Local變數(shù)就是寫(xiě)在函數(shù)內(nèi)的變數(shù)有補(bǔ)static修飾詞則為static變數(shù)(靜態(tài)變數(shù))沒(méi)有補(bǔ)static修飾詞則為Auto變數(shù)(自動(dòng)變數(shù))static的變數(shù)在程式開(kāi)始RUN之前就存在,且已經(jīng)設(shè)好初值,程式結(jié)束後才會(huì)還掉所佔(zhàn)記憶體(生命期)寫(xiě)了extern表示只是宣告,不是定義(define)Local變數(shù)就只能在該函數(shù)內(nèi)存取Global變數(shù)則只要看得見(jiàn)它的任一函數(shù)都能存取它宣告之後就看得見(jiàn),沒(méi)宣告就定義則看作同時(shí)宣告了注意main()也是函數(shù),沒(méi)有特別偉大!27Global,StaticLocal,Auto變數(shù)#include<stdio.h>
externintx;/*只有宣告,還不知道位置在何處?*/intfa();intfb(){intans=0;return++ans;}intmain(){intkk=123;cout<<"fa()="<<fa()<<fa()<<fa()<<kk<<endl;cout<<"fb()="<<fb()<<fb()<<fb()<<endl;return0;/*0inmain()meansOK*/}intx,y;/*真的x在這,也可以寫(xiě)在另一個(gè)file中*/intfa(){/*…*}寫(xiě)了extern表示只是宣告,不是定義(define)28StaticGlobal變數(shù)#include<stdio.h>#defineBUFSIZE100
staticcharbuf[BUFSIZE];
staticintbufp=0;intgetch(){/*...*/}voidungetch(intc){/*...*/}InformationHiding?也參考stack的push和pop寫(xiě)在同一獨(dú)立file中,push和pop共享dataFunctionsinanotherfilecanNOTseethesestatic
variable29再談StaticGlobal變數(shù)#include<stdio.h>#defineRAND_MAX65535
staticunsignedlongseed=0;/*global*/intrand(){
seed=seed*1103515245+12345;returnseed%(RAND_MAX+1);}voidsrand(intnewseed){
seed=newseed;}
程式庫(kù)中的PseudorandomnumberInformationHiding?只有rand和srand看得見(jiàn)seed30register變數(shù),volatile變數(shù)#include<stdio.h>enum{BUFSIZE=100,NSTU=60};
registerintwrong;/*thisiswrong,global不可*/volatileinthaha;voidmyfun(registerintx){
registerintyy,i;/*OK*/int*p;/*...*/p=&yy;/*thisiswrong*/}參考K&R課本4.7節(jié)拜託Compiler儘可能安排在CPU內(nèi)的暫存器31volatile變數(shù)#include<stdio.h>volatileinthaha;/*tellcompiler…*/intmain(){intk;doubleans;for(k=1;k<=99;++k){/*...*/ans=haha*haha;/*donotoptimize*/printf("ans=%f\n",ans);}}參考K&R課本4.7節(jié)警告Compiler這變數(shù)可能會(huì)被別的程式改變32問(wèn)題與思考(Why?)只能用這些datatype嗎?Userdefineddatatype?考慮寫(xiě)程式處理全班成績(jī)資料,包括加總平均並排序(Sort)然後印出一份照名次排序的以及一份照學(xué)號(hào)排序的全班資料如何做Sort(排序)?Sort時(shí)兩學(xué)生資料要對(duì)調(diào),要如何對(duì)調(diào)?有很多array?存學(xué)號(hào)的array,存姓名的array?存成績(jī)的array?…Bubblesort,Insertionsort,Selectionsort33Whystruct?Struct可以把相關(guān)資料group在一起structstudentx[99],tmp;/*…*/tmp=x[i];x[i]=x[k];x[k]=tmp;增加程式可讀性程式更容易維護(hù)34WhatisObject?Class?(1/2)object就是“東西〞,就是以前的“變數(shù)〞class就是“類別〞,某種東西的型別intm,n;/*int是整數(shù)類別*//*m,n都是變數(shù)*/Studentx,y;/*Student是我們自訂類別*//*x,y都是object*/35WhatisObject?Class?(2/2)objectisaninstanceofsomeclass文法上class就是以前的structclassStudent{public:/*…與寫(xiě)struct同*/};structNode{private:/*…與寫(xiě)class同*/};36ObjectConcept(1/3)Whyusingclass支援OOP(物件導(dǎo)向ObjectOrientedProgramming)
又譯作
個(gè)體導(dǎo)向程式設(shè)計(jì)考慮Stack堆疊:讓東西用起來(lái)更像東西ADT(AbstractDataType)把data以及對(duì)該些data有關(guān)的方法(method)或稱函數(shù)(function,函式)封裝(encapsulate)在一個(gè)程式單元方便使用37ObjectConcept(2/3)Object-OrientedAnalysis(OOA)Goal:UnderstandthedomainObject-OrientedDesign(OOD)Goal:Designasolution,amodelofthedomaininwhichthedesiredactivitiesoccurObject-OrientedProgramming(OOP)Goal:ImplementthesolutionNote:AGoodDesignis2/3BeforeYouHittheKeyboard38OOconcept(3/3)#include"mystk.h"#include<iostream.h>intmain(){Stackxo;/*xoisanobject,itisaStack*/xo.push(880);/*要求xo把880push進(jìn)去*/xo.push(770);xo.push(53);
while(!xo.isempty()){cout<<""<<xo.pop();/*要求xo吐出頂端元素*//*......*/
}cout<<endl;return0;}How?如何製做Stack?39Struct–自訂資料型別(1/5)#include<stdio.h>structStudent{longsid;charname[9];/*可存四個(gè)Big5中文*/floatscore[13];/*每人最多修13科
*/};/*注意struct與class之分號(hào)不能省掉*/intmain(){
struct
Studentx;/*C++和C99不用寫(xiě)struct
*/x.sid=123;/*dotnotation*/strcpy(,"張大千");/*注意字串不能=*//*用loop把成績(jī)讀入x.score[?]*/}考慮寫(xiě)個(gè)程式處理學(xué)生的成績(jī)資料,如何表示一個(gè)學(xué)生的資料?想一想...40struct---Structure(2/5)structDate{
intday,month,year;};voidmain(){structDatebirthday={14,2,1999};structDatetoday;today.day=28;today.month=2;today.year=2003;
printf("Thisyearis%d",today.year);…}today2822003today.daytoday.monthtoday.yearbirthday1421999birthday.daybirthday.monthbirthday.yearbirthdaytoday41Structure(3/5)GrouprelatedfieldsintoastructuretypedefstructdateDate;structdate{
intday,month,year;};structdatetoday;Datetoday;C99和C++則只要寫(xiě)
datetoday;42Structure(4/5)兩種定義一次寫(xiě)完typedefstructdate{
intday,month,year;}Date;/*Date為type*/
structdatetoday;orDatetoday;注意這意思不同!structdate{
intday,month,year;}Date;/*Date為變數(shù)*/43Structure(5/5)Student是typetypedefstructstudent{
longsid;charname[9];floatheight;doublewet;/*weight*/}Student;structstudent{
longsid;charname[9];floatheight;doublewet;}Student,stmp,x[99];Whataboutthis?Student是變數(shù)44NestedStruct,ArrayofStructtypedefstruct{intd,m,y;}Date;
typedefstruct{
charname[49];/*enough?*/
doubleaverageScore;
Datedob;/*dateofbirth*/}Student;/*一學(xué)生*/
typedefstruct{
Studentstud[66];intnumStud;
}SomeClass;/*一班*/SomeClasscsie1a;Youcanalsocreateanarrayasdynamicvariableusingmalloc().Thearraysizeneednotbefixedatcompiletime.45StructureasOutputParametervoidscan_date(Date*aday){intdd,mm,yy;scanf("%d%d%d",&dd,&mm,&yy);(*aday).d=dd;(*aday).m=mm;(*aday).y=yy;}intmain(){Datetoday;scan_date(&today);print_date(today);...}Weneedtopasspointertostructuretoafunctionthatmodifiesthestructure,similartointeger.typedefstructdate{
intd,m,y;}Date;46PointertoStructure(1/2)voidscan_date(Date*aday){intdd,mm,yy;scanf("%d%d%d",&dd,&mm,&yy);aday->d=dd;aday->m=mm;aday->y=yy;}Ashorthand:(*aday).dsameasaday->d(*aday).msameasaday->mtypedefstructdate{
intd,m,y;}Date;47PointertoStructure(2/2)voidscan_date(Date*aday){scanf("%d%d%d",&aday->d,&aday->m,&aday->y);}Ifwewanttosetthefieldsofastructurebyscanf,weneedtopasstheaddressofthesefields.scan_date(&today);typedefstructdate{
intd,m,y;}Date;48StructureasParametervoidprint_date(Dateaday){printf("%d/%d/%d",aday.d,aday.m,aday.y);}/*callbyvalue*/voidscan_date(Date*aday){scanf("%d%d%d",&aday->d,&aday->m,&aday->y);}/*passaddresstopointer*/typedefstructdate{
intd,m,y;}Date;49Comparingcontentofstructuretypedefstruct{intd,m,y;}Date;intmain(){Dateday1={11,2,1999};Dateday2={1,12,1999};...if(day1==day2)/*wrong*/…}
Althoughwecanuse"="tocopystructure,wecannotcomparestructureby"==".50問(wèn)題與思考(How?)如何表示LinkedList?如何表示Stack,Queue?Stack與Queue的應(yīng)用如何表示Tree?如何儲(chǔ)存---BinaryTreeRepresentationofTreeTree的應(yīng)用?Tree的traversalExpressiontreevs.parsingtree512002梅竹開(kāi)幕TakeaBreak!52FromCtoC++(1/2)C++最重要的就是class(類別)class其實(shí)是struct的延伸InC++,wecanputrelated
functionswiththerelated
datainstruct(class)所以C++的class就是C的struct加上一些規(guī)定Java把struct拿掉了!且union也沒(méi)了!WhyusingstructinC?Grouprelateddatatogetherclass有何用?支援OOP(物件導(dǎo)向ObjectOrientedProgramming)
又譯作
個(gè)體導(dǎo)向程式設(shè)計(jì)考慮Stack堆疊...53FromCtoC++(2/2)class類別vs.struct結(jié)構(gòu)C++除了class外還有一些雕蟲(chóng)小技I/OstreamfacilityandotherClassLibraryParameterpassing?(C++可指定callbyreference)functionnameoverloading(函數(shù)名稱重複使用)Operatoroverloading,…n=5+38;x=25.8+3.69;inlinefunction?(只影響編譯與執(zhí)行效率,不影響答案)templatefunction,templateclass54FunctionnameOverloading/*再寫(xiě)一個(gè)函數(shù)可以將兩double數(shù)對(duì)調(diào),C++專有*/#include<stdio.h>voidswap(int&x,int&y){inttemp;temp=x;x=y;y=temp;}voidswap(double&x,double&y){doubletemp;temp=x;x=y;y=temp;}(C++專有)C++允許同名的function,但注意參數(shù)55用array來(lái)做STACK(1/2)
sptrStackPointerintsptr;01-1intx[99];voidpush(inty){
++sptr;x[sptr]=y;}intans=pop();Initialization:sptr=-1;/*empty*/需要一個(gè)array和一個(gè)整數(shù)push(456);
push(3388);
4563388intpop(){
inttmp=x[sptr];--sptr;returntmp;}9856用array來(lái)做STACK(2/2)
staticintx[99];/*別的檔案看不到這*/
staticintsptr=-1;/*emptystack*/voidpush(inty){++sptr;/*movestackpointer*/x[sptr]=y;/*putthedataythere*/}intpop(){returnx[sptr--];/*注意--寫(xiě)後面*/}/*其它相關(guān)function例如isempty()*/57使用STACKexternvoidpush(int);/*宣告*/externintpop();#include<stdio.h>intmain(){push(543);push(881);printf("%d\n",pop());}/*可以用!但假設(shè)要兩個(gè)Stack呢?*/58MoreaboutSTACK(1/3)/*假設(shè)要兩個(gè)Stack呢?*/解法之一==>使用兩個(gè)array,並把a(bǔ)rray當(dāng)參數(shù) push(ary2,x);ans=top(ary2);但是這樣該些array必須開(kāi)放讓使用者知道 要讓宣告extern就看得到,不可再用staticGlobal 違反不必讓使用者知道push到哪去的Information Hiding原則! (或是該些array要定義在使用者程式裡面)59MoreaboutSTACK(2/3)/*假設(shè)要兩個(gè)Stack呢?*/解法之二==>整個(gè)檔案複製到另一個(gè)file,並把各相 關(guān)函數(shù)名稱都改掉,例如push2,pop2,…==>array與變數(shù)名稱不用改!Why? (因?yàn)閟taticGlobal)但是這樣也不是很方便,函數(shù)名稱一大堆 假設(shè)要三個(gè)Stack呢?四個(gè)呢?… (不過(guò)這比前面使用不同array的方法好!)60MoreaboutSTACK(3/3)/*假設(shè)要兩個(gè)Stack呢?*//*假設(shè)要三個(gè)Stack呢?四個(gè)?五個(gè)...*//*有沒(méi)有更方便直接的方法?*/==>usingC++Class todefineaStackasaSoftwareComponent (軟體元件或零件)Stackx;Stacky;x.push(13579);y.push(258);y.push(x.pop());61Stack--classexample(1/2)mystk.hclassStack{//private:longdata[99];/*直接寫(xiě)99不是好習(xí)慣*/intsptr;public:Stack();/*constructor*/voidpush(long);longpop();
boolisempty();};/*classStack*/
bool要新版的C++才有62Stack--classexample(2/2)mystk.cpp#include"mystk.h"#include<iostream.h>
Stack::Stack(){sptr=-1;}/*Constructor*/voidStack::push(longxx){/*注意Stack::*/data[++sptr]=xx;}longStack::pop(){returndata[sptr--];}
boolStack::isempty(){returnsptr==-1;}//...bool要新版的C++才有這是實(shí)作出Stack,前面mystk.h只是宣告Initialization工作要寫(xiě)在特殊函數(shù)63Stack(使用)mymain.cpp#include"mystk.h"#include<iostream.h>intmain(){Stackxo,brandy;xo.push(880);xo.push(770);xo.push(53);
while(!xo.isempty()){cout<<""<<xo.pop();
}cout<<endl;return0;}64Stack(使用)如何執(zhí)行?#include"mystk.h"#include<iostream.h>intmain(){Stackxo,brandy;xo.push(880);xo.push(770);xo.push(53);
while(!xo.isempty()){cout<<""<<xo.pop();
}cout<<endl;/*newLine*/return0;}53770880gccmymain.cppmystk.cpp./a.outgcc–cmystk.cppgccmymain.cppmystk.o./a.out65Stack(使用)可全寫(xiě)在一file,但??classStack{//private:longdata[99];/*直接寫(xiě)99不是好習(xí)慣*/intsptr;public:Stack(){sptr=-1;};voidpush(longxx){data[++sptr]=xx;}longpop(){returndata[sptr--];}
boolisempty(){returnsptr==-1;}
};
#include<iostream.h>intmain(){Stackxo,brandy;xo.push(880);xo.push(770);xo.push(53);
while(!xo.isempty()){cout<<""<<xo.pop();
}cout<<endl;return0;}壞處:假設(shè)要reuseStack呢?切下來(lái)另存檔案?不方便!不符合OOP原則這樣這些會(huì)變inlinefunction66class內(nèi)要用enum生出常數(shù)/***g++thisfile.cpp;./a.out***/#include<iostream>usingnamespacestd;#include<stdio.h>classStack{//private:
public:enum{size=99};/*正確的好習(xí)慣*/
private:longdata[size];/*直接寫(xiě)99不是好習(xí)慣*/intsptr;/*stackpointer*/
public:Stack();voidpush(long);longpop();boolisempty();};/*classStack*/Stack::Stack(){}voidStack::push(longy){}longStack::pop(){}boolStack::isempty(){}intmain(){
Stackx;cout<<"Hahaha"<<endl;cout<<"stacksize="<<Stack::size<<endl;cout<<"Sizeofx="<<x.size<<endl;}67問(wèn)題與思考(Stacksize)Stack內(nèi)的array一定要固定99元素嗎?
==>usingpointer就可做出可變大小的arrayclassStack{
long*data;intmySize;Stack(intsz=99);
/*...*/};Stack::Stack(intsz){sptr=-1;mySize=sz;data=(long*)malloc(sz*sizeof(long));}使用時(shí)指定大小:Stackxo(66);Stackbrandy;Default參數(shù)68Stack應(yīng)用again(1/2)InfixexpressionPostfixexpressionInfixexpression:12+(2*3)/5Prefix:+12/*235*+/Postfix:1223569問(wèn)題與思考(Why??)現(xiàn)在用class製作軟體零件(元件),雖可以有許多個(gè)long的Stack假設(shè)要一個(gè)long的Stack以及一個(gè)double的Stack呢?甚至一個(gè)Student的Stack呢??Copy來(lái)改並換class名稱嗎?No==>usingC++templateClass(樣版類別)70C++Template(樣版)TemplatesprovidedirectsupportforgenericprogrammingTheC++templatemechanismallowsatypetobeaparameterinthedefinitionofaclassorafunctiondefinerspecifiesthecontainerclassintermsofthatargumentusersspecifywhatthetypeofcontainedobjectsisThetemplateimplementationisamechanismthatgeneratestypeswhenneededbasedontheuser’sspecification(compiler幫忙copy去改
)Everymajorstandardlibraryabstractionisrepresentedasatemplate71C++FunctionTemplate(樣版函數(shù))template<classT>voidswap(T&x,T&y){Ttemp;temp=x;x=y;y=temp;}intmain(){intm=38,n=49;doublea=12.34,b=567.135;swap(a,b);swap(m,n);/**…**/}Whenatemplatefunctioniscalled,thetypeofthefunctionargumentsdeterminewhichversionofthetemplateisused.Thatisthetemplateargumentsarededucedfromthefunctionarguments如何使用swap()函數(shù)?72C++ClassTemplate如何有多個(gè)可處理不同datatype的堆疊?Template<classT>classStack{Tdata[99];intsptr;public:Stack();voidpush(Tx);Ttop(void);
voidpop(void);
intempty();//...};Stack<T>::Stack(){sptr=-1;}/*…*/templatedeclaration,TistypeargumentTisuesdexactlylikeothertypenamesStack<int>xo;Stack<double>brandy;Stack<Student>haha;/*…*/ClassnameisusedexactlylikeothersButyouhavetospecifythetypein<>不該改的不要改,例如intsptr;當(dāng)然不改73Stack(使用Library的stack)#include<stack>#include<iostream>usingnamespacestd;/*wheretheLibraryin*/intmain(){
stack<int>xo;/*注意用法stack<int>*/
stack<double>brandy;/*注意用法*/xo.push(880);xo.push(770);xo.push(53);
while(!xo.empty()){/*注意empty不是isempty*/cout<<""<<xo.top();/*注意用top()*/xo.pop();/*popisvoidtype*/
}cout<<endl;/*newLine*/return0;}53770880gccthisfile.cpp./a.outC++程式庫(kù)的stack是TemplateLibrary74Stack應(yīng)用again(2/2)使用堆疊把infixpostfixStack內(nèi)放運(yùn)算符號(hào)(operator)和左括號(hào)使用堆疊計(jì)算postfix的答案Stack內(nèi)放運(yùn)算元素(operand)或說(shuō)value(整數(shù)或?qū)崝?shù))75認(rèn)真看classC語(yǔ)言的struct目的是把相關(guān)資料group在一起class(類別)就是原來(lái)的structwithsomeregulationsclassisauser-defined
datatype,自訂的,抽象的所以class是AbstractData
Type(ADT)ADT就是把data以及對(duì)這些data有關(guān)的動(dòng)作(method,就是
function)一起封藏(Encapsulate)在一個(gè)程式單元(programunit)之內(nèi),例如C++用class來(lái)封藏Class可用來(lái)設(shè)計(jì)軟體元件(SoftwareComponent)Class內(nèi)的datamember/methodmember存取控制:private,protected,public(C++與Java寫(xiě)法不同)Constructor?Destructor?DefaultConstructor?…Java沒(méi)有Destructor,但有finalize函數(shù)76Structvs.Class(1/2)#include<iostream.h>classStudent{//假設(shè)改為structStudent{…?longsid;//defaultisprivateforclass};//defaultispublicforstructintmain(){Studentx;x.sid=123;//compile錯(cuò),accessnotallowedcout<<"=="<<x.sid<<endl;//compile錯(cuò)return0;}假設(shè)改為structStudent則變沒(méi)錯(cuò)!Why?77Structvs.Class(2/2)#include<iostream.h>
classStudent{//private:longsid;
public:showNumber(){returnsid;}setId(longxx){sid=xx;}};intmain(){Studentx,y;x.setId(123);//OK,透過(guò)publicfunctionsetId()
cout<<"=="<<x.showNumber()<<endl;//OKreturn0;}78Classvs.ObjectObjectisaninstanceofsomeclassintx;floatyy;Object(物件,個(gè)體,東西)--就是以前的變數(shù)classStudent{longsid;charname[9];};Studentx,y[99],tempstu;structStudent{longsid;charname[9];};Studentx,y[99],tempstu;79Class(Object)Constructor1/4#include<iostream.h>classStudent{//private:longsid;public:showNumber(){returnsid;}setId(longxx){sid=xx;}
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 月嫂測(cè)試試題及答案
- 外科臨床考試試題及答案
- 必考知識(shí)清單2024年紡織品設(shè)計(jì)師證書(shū)考試試題及答案
- 創(chuàng)建自信的2024年紡織品檢驗(yàn)員證書(shū)的試題及答案
- 提高通過(guò)率的2024年紡織品檢驗(yàn)員證書(shū)試題及答案
- 了解紡織品檢驗(yàn)流程試題及答案
- 江蘇中考南通試題及答案
- 商業(yè)美術(shù)設(shè)計(jì)師2024年考試題型分析及答案
- 口令游戲面試題及答案
- 閉式冷卻塔和開(kāi)式冷卻塔的集水盤材質(zhì)有哪些區(qū)別
- 織帶繪圖方法
- 地下車庫(kù)地坪施工工藝工法標(biāo)準(zhǔn)
- 生物化學(xué)工程基礎(chǔ)(第三章代謝作用與發(fā)酵)課件
- 國(guó)家開(kāi)放大學(xué)一網(wǎng)一平臺(tái)電大《可編程控制器應(yīng)用實(shí)訓(xùn)》形考任務(wù)1-7終結(jié)性考試題庫(kù)及答案
- 農(nóng)村戶口分戶協(xié)議書(shū)(6篇)
- (部編版一年級(jí)下冊(cè))語(yǔ)文第七單元復(fù)習(xí)課件
- SQ-02-綠色食品種植產(chǎn)品調(diào)查表0308
- 視頻結(jié)構(gòu)化大數(shù)據(jù)平臺(tái)解決方案
- 麗聲北極星分級(jí)繪本第二級(jí)上Dinner for a Dragon 教學(xué)設(shè)計(jì)
- 活躍氣氛的開(kāi)場(chǎng)小游戲「培訓(xùn)破冰前必備」
- 光伏發(fā)電項(xiàng)目安全專項(xiàng)投資估算方案
評(píng)論
0/150
提交評(píng)論