二进位也可以很有趣 - 交通大学_第1页
二进位也可以很有趣 - 交通大学_第2页
二进位也可以很有趣 - 交通大学_第3页
二进位也可以很有趣 - 交通大学_第4页
二进位也可以很有趣 - 交通大学_第5页
已阅读5页,还剩141页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

ObjectOrientedConcept蔡文能交通大學資訊工程學系OOA,OOD,

OOP/~tsaiwn/oop/1AgendaReview:DataRepresentationinthecomputerWhyusingstruct?WhatisObject?Whatisclass?OOConcept?Whyusingclass?Howtobuildacomponent?OOfeaturesEncapsulation,InformationHiding,Inheritance,Polymorphism2電腦內如何儲存資料?如何表示文字?ASCII?EBCDIC?…如何表示數值?整數?(char,short,int,long)longlong,boolean?實數?(float,double)數值的範圍?實數數值的準確度(precision)其它?問題與思考(DataRepresentation)longlongisintroducedinC99boolisintroducedinC++3問題與思考(如何表示文字?)#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問題與思考(如何表示文字?)ccbsd2:tsaiwn>gcctestc.cccbsd2:tsaiwn>./a.out==AabcYou38==ccbsd2:tsaiwn>先把前面程式存入testc.c編譯與連結執行5問題與思考(中文碼?)#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問題與思考(中文碼?)ccbsd2:tsaiwn>gcctestc.cccbsd2:tsaiwn>./a.out==大家好==ccbsd2:tsaiwn>先把前面程式存入testc.c編譯與連結執行7實數與準確度(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實數準確度七位多ccbsd2:precision/>gccprecision.cccbsd2:precision/>./a.outBeforeloop,x=1234567.250000firsty=1234567.250100Afterloop,x=1234567.250000ccbsd2:precision/>

float實數佔用32bits9double實數準確度#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實數準確度十五位多ccbsd2:precision/>gccprecdbl.cccbsd2:precision/>./a.outBeforeloop,x=1234567.200000firsty=1234567.200100Afterloop,x=1234568.000001ccbsd2:precision/>

double實數佔用64bits11SummaryaboutDataRepresentation變數(variable)就是佔住記憶體一小塊地方有個名字變數名字要用字母開頭變數的種類(類型):整數:char,(byte),short,int,long,longlong(C99才有)實數:float,double,longdouble數值的絕對值太大無法存入規定格式稱Overflow數值的絕對值太小無法存入規定格式被電腦當作0存起來稱Underflow,實數才會!整數沒有underflowJava語言有8種primitivedatatypeboolean,byte,char,short,int,long,float,doublefloat的準確度只有二進位24位,約十進位7位強double的準確度只有二進位53位,約十進位15位強自訂型別(UserDefinedDataType)12整數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實數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=無窮大=Inf=Inf=Inf14float實數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再談變數Variable變變變變數當然會變才叫變數–廢話!變數命名規則與慣例?averageScore,

n,x變數放在電腦的記憶體–何處?與程式一起,與程式分離?–由Linker負責堆疊區(STACK)?

嘿洗蝦密碗糕啊?變數的能見範圍(Scope)?或說有效範圍函數(函式)內的變數:Localvariable局部(區域)變數函數外的變數:Globalvariable整體變數變數何時生出?何時死掉?生命期

(Lifetime)?16變數分類依能見範圍(Scope,或說有效範圍)?Local區域vs.Global整體依何時給它記憶體位置(稱作binding)Staticvariable:靜態變數,Run之前(compile/Link)Dynamicvariable:動態變數,Run之後才會做binding(就是Run之後才給它位置)自動要自動還:auto變數(function內沒寫static)手動要:使用malloc或calloc要,用free還(C++用new和delete)auto變數在stack堆疊手動要的(malloc,calloc)在Heap堆積17變數(Variable)

的Scope,Lifetime變數的能見範圍(Scope,或說有效範圍)函數(函式)內的變數:Localvariable局部(區域)變數:只有在函數內有效函數外的變數:Globalvariable(整體變數)Globalvariable:宣告之後就一直有效變數生命期(Lifetime)?靜態變數從程式開始Run就“出生〞Auto變數在進入函數時生出,離開函數時死掉(把記憶體還給系統)沒有宣告static的:Local變數就是Auto變數18Global變數vs.Local變數#include<iostream.h>intx=38,y=250;/*Global*/voidsub1(int);/*見後面程式*/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變數vs.Local變數voidsub1(inty){cout<<"y="<<y<<endl;x++;/*Global的x,因為Local沒有x*/::x++;/*也是Global的x*/y++;/*因為y是passbyvalue,回去不會變*/::y++;/*是Global的y*/return;/*不寫也可以*/}(Cont)passbyvalue就是callbyvalue講法不同而已

20StaticLocal變數#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變數intfa(){intx=1;returnx++;/*先取其值,再做++*/}intfb(){static//把static寫在以下左方也一樣intx=1;//注意staticintx=1;returnx++;}(Cont)22StaticLocal變數,evaluation順序#include<stdio.h>intfa();/*宣告*/intfb();intmain(){/*不同系統可能不同答案*/printf("fa()=%d%d%d\n", fa(),fa(),fa());printf("fb()=%d%d%d\n", fb(),fb(),fb());return0;/*0inmain()meansOK*/}//intfa()…也可以寫在另一個檔案內23Evaluation順序#include<stdio.h>intgg(intx){staticans=0;ans=x+ans*ans;returnans;}intmain(){/*不同系統可能不同答案!*/inthaha=gg(1)+gg(2)+gg(3);/*先做哪個gg()?*/printf("haha=%d\n",haha);return0;}

expression中有多個函數叫用會先做哪個gg()?C/C++沒有規定!所以看寫compiler的人高興

24Auto變數不可佔太多memoryAuto變數就是沒寫static的Local變數Auto變數是在進入函數時才在STACK區安排記憶體,在離開函數(return)時就還掉(改變StackPointer)STACK區一般不會很大(幾拾KBytes)Auto變數用STACK區,所以太大的array不能用叫用函數時,returnaddress也會被推入

STACK

參數傳遞也是用STACK區C/C++推入參數時是先推入最後一個參數,這使得第一個參數會在堆疊的最上方,進入函數時,STACK中

returnaddress之下就是第一個參數C/C++離開函數時,函數不負責拿掉STACK中

的參數,那是叫用函數那個程式的責任!(與其它語言不同)25Auto變數佔用STACK區memoryAuto變數就是沒寫static的Local變數CPUIPSPInstructionPointerStackPointer系統區系統區程式+靜態dataHEAP堆積malloc(),new()STACK(參數與Auto變數)Heap由上往下長Stack由下往上長26Static變數?Global變數都是static的變數Local變數就是寫在函數內的變數有補static修飾詞則為static變數(靜態變數)沒有補static修飾詞則為Auto變數(自動變數)static的變數在程式開始RUN之前就存在,且已經設好初值,程式結束後才會還掉所佔記憶體(生命期)寫了extern表示只是宣告,不是定義(define)Local變數就只能在該函數內存取Global變數則只要看得見它的任一函數都能存取它宣告之後就看得見,沒宣告就定義則看作同時宣告了注意main()也是函數,沒有特別偉大!27Global,StaticLocal,Auto變數#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在這,也可以寫在另一個file中*/intfa(){/*…*}寫了extern表示只是宣告,不是定義(define)28StaticGlobal變數#include<stdio.h>#defineBUFSIZE100

staticcharbuf[BUFSIZE];

staticintbufp=0;intgetch(){/*...*/}voidungetch(intc){/*...*/}InformationHiding?也參考stack的push和pop寫在同一獨立file中,push和pop共享dataFunctionsinanotherfilecanNOTseethesestatic

variable29再談StaticGlobal變數#include<stdio.h>#defineRAND_MAX65535

staticunsignedlongseed=0;/*global*/intrand(){

seed=seed*1103515245+12345;returnseed%(RAND_MAX+1);}voidsrand(intnewseed){

seed=newseed;}

程式庫中的PseudorandomnumberInformationHiding?只有rand和srand看得見seed30register變數,volatile變數#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節拜託Compiler儘可能安排在CPU內的暫存器31volatile變數#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節警告Compiler這變數可能會被別的程式改變32問題與思考(Why?)只能用這些datatype嗎?Userdefineddatatype?考慮寫程式處理全班成績資料,包括加總平均並排序(Sort)然後印出一份照名次排序的以及一份照學號排序的全班資料如何做Sort(排序)?Sort時兩學生資料要對調,要如何對調?有很多array?存學號的array,存姓名的array?存成績的array?…Bubblesort,Insertionsort,Selectionsort33Whystruct?Struct可以把相關資料group在一起structstudentx[99],tmp;/*…*/tmp=x[i];x[i]=x[k];x[k]=tmp;增加程式可讀性程式更容易維護34WhatisObject?Class?(1/2)object就是“東西〞,就是以前的“變數〞class就是“類別〞,某種東西的型別intm,n;/*int是整數類別*//*m,n都是變數*/Studentx,y;/*Student是我們自訂類別*//*x,y都是object*/35WhatisObject?Class?(2/2)objectisaninstanceofsomeclass文法上class就是以前的structclassStudent{public:/*…與寫struct同*/};structNode{private:/*…與寫class同*/};36ObjectConcept(1/3)Whyusingclass支援OOP(物件導向ObjectOrientedProgramming)

又譯作

個體導向程式設計考慮Stack堆疊:讓東西用起來更像東西ADT(AbstractDataType)把data以及對該些data有關的方法(method)或稱函數(function,函式)封裝(encapsulate)在一個程式單元方便使用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進去*/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];/*可存四個Big5中文*/floatscore[13];/*每人最多修13科

*/};/*注意struct與class之分號不能省掉*/intmain(){

struct

Studentx;/*C++和C99不用寫struct

*/x.sid=123;/*dotnotation*/strcpy(,"張大千");/*注意字串不能=*//*用loop把成績讀入x.score[?]*/}考慮寫個程式處理學生的成績資料,如何表示一個學生的資料?想一想...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++則只要寫

datetoday;42Structure(4/5)兩種定義一次寫完typedefstructdate{

intday,month,year;}Date;/*Date為type*/

structdatetoday;orDatetoday;注意這意思不同!structdate{

intday,month,year;}Date;/*Date為變數*/43Structure(5/5)Student是typetypedefstructstudent{

longsid;charname[9];floatheight;doublewet;/*weight*/}Student;structstudent{

longsid;charname[9];floatheight;doublewet;}Student,stmp,x[99];Whataboutthis?Student是變數44NestedStruct,ArrayofStructtypedefstruct{intd,m,y;}Date;

typedefstruct{

charname[49];/*enough?*/

doubleaverageScore;

Datedob;/*dateofbirth*/}Student;/*一學生*/

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問題與思考(How?)如何表示LinkedList?如何表示Stack,Queue?Stack與Queue的應用如何表示Tree?如何儲存---BinaryTreeRepresentationofTreeTree的應用?Tree的traversalExpressiontreevs.parsingtree512002梅竹開幕TakeaBreak!52FromCtoC++(1/2)C++最重要的就是class(類別)class其實是struct的延伸InC++,wecanputrelated

functionswiththerelated

datainstruct(class)所以C++的class就是C的struct加上一些規定Java把struct拿掉了!且union也沒了!WhyusingstructinC?Grouprelateddatatogetherclass有何用?支援OOP(物件導向ObjectOrientedProgramming)

又譯作

個體導向程式設計考慮Stack堆疊...53FromCtoC++(2/2)class類別vs.struct結構C++除了class外還有一些雕蟲小技I/OstreamfacilityandotherClassLibraryParameterpassing?(C++可指定callbyreference)functionnameoverloading(函數名稱重複使用)Operatoroverloading,…n=5+38;x=25.8+3.69;inlinefunction?(只影響編譯與執行效率,不影響答案)templatefunction,templateclass54FunctionnameOverloading/*再寫一個函數可以將兩double數對調,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,但注意參數55用array來做STACK(1/2)

sptrStackPointerintsptr;01-1intx[99];voidpush(inty){

++sptr;x[sptr]=y;}intans=pop();Initialization:sptr=-1;/*empty*/需要一個array和一個整數push(456);

push(3388);

4563388intpop(){

inttmp=x[sptr];--sptr;returntmp;}9856用array來做STACK(2/2)

staticintx[99];/*別的檔案看不到這*/

staticintsptr=-1;/*emptystack*/voidpush(inty){++sptr;/*movestackpointer*/x[sptr]=y;/*putthedataythere*/}intpop(){returnx[sptr--];/*注意--寫後面*/}/*其它相關function例如isempty()*/57使用STACKexternvoidpush(int);/*宣告*/externintpop();#include<stdio.h>intmain(){push(543);push(881);printf("%d\n",pop());}/*可以用!但假设要兩個Stack呢?*/58MoreaboutSTACK(1/3)/*假设要兩個Stack呢?*/解法之一==>使用兩個array,並把array當參數 push(ary2,x);ans=top(ary2);但是這樣該些array必須開放讓使用者知道 要讓宣告extern就看得到,不可再用staticGlobal 違反不必讓使用者知道push到哪去的Information Hiding原則! (或是該些array要定義在使用者程式裡面)59MoreaboutSTACK(2/3)/*假设要兩個Stack呢?*/解法之二==>整個檔案複製到另一個file,並把各相 關函數名稱都改掉,例如push2,pop2,…==>array與變數名稱不用改!Why? (因為staticGlobal)但是這樣也不是很方便,函數名稱一大堆 假设要三個Stack呢?四個呢?… (不過這比前面使用不同array的方法好!)60MoreaboutSTACK(3/3)/*假设要兩個Stack呢?*//*假设要三個Stack呢?四個?五個...*//*有沒有更方便直接的方法?*/==>usingC++Class todefineaStackasaSoftwareComponent (軟體元件或零件)Stackx;Stacky;x.push(13579);y.push(258);y.push(x.pop());61Stack--classexample(1/2)mystk.hclassStack{//private:longdata[99];/*直接寫99不是好習慣*/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++才有這是實作出Stack,前面mystk.h只是宣告Initialization工作要寫在特殊函數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(使用)如何執行?#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(使用)可全寫在一file,但??classStack{//private:longdata[99];/*直接寫99不是好習慣*/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;}壞處:假设要reuseStack呢?切下來另存檔案?不方便!不符合OOP原則這樣這些會變inlinefunction66class內要用enum生出常數/***g++thisfile.cpp;./a.out***/#include<iostream>usingnamespacestd;#include<stdio.h>classStack{//private:

public:enum{size=99};/*正確的好習慣*/

private:longdata[size];/*直接寫99不是好習慣*/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問題與思考(Stacksize)Stack內的array一定要固定99元素嗎?

==>usingpointer就可做出可變大小的arrayclassStack{

long*data;intmySize;Stack(intsz=99);

/*...*/};Stack::Stack(intsz){sptr=-1;mySize=sz;data=(long*)malloc(sz*sizeof(long));}使用時指定大小:Stackxo(66);Stackbrandy;Default參數68Stack應用again(1/2)InfixexpressionPostfixexpressionInfixexpression:12+(2*3)/5Prefix:+12/*235*+/Postfix:1223569問題與思考(Why??)現在用class製作軟體零件(元件),雖可以有許多個long的Stack假设要一個long的Stack以及一個double的Stack呢?甚至一個Student的Stack呢??Copy來改並換class名稱嗎?No==>usingC++templateClass(樣版類別)70C++Template(樣版)TemplatesprovidedirectsupportforgenericprogrammingTheC++templatemechanismallowsatypetobeaparameterinthedefinitionofaclassorafunctiondefinerspecifiesthecontainerclassintermsofthatargumentusersspecifywhatthetypeofcontainedobjectsisThetemplateimplementationisamechanismthatgeneratestypeswhenneededbasedontheuser’sspecification(compiler幫忙copy去改

)Everymajorstandardlibraryabstractionisrepresentedasatemplate71C++FunctionTemplate(樣版函數)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()函數?72C++ClassTemplate如何有多個可處理不同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;當然不改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++程式庫的stack是TemplateLibrary74Stack應用again(2/2)使用堆疊把infixpostfixStack內放運算符號(operator)和左括號使用堆疊計算postfix的答案Stack內放運算元素(operand)或說value(整數或實數)75認真看classC語言的struct目的是把相關資料group在一起class(類別)就是原來的structwithsomeregulationsclassisauser-defined

datatype,自訂的,抽象的所以class是AbstractData

Type(ADT)ADT就是把data以及對這些data有關的動作(method,就是

function)一起封藏(Encapsulate)在一個程式單元(programunit)之內,例如C++用class來封藏Class可用來設計軟體元件(SoftwareComponent)Class內的datamember/methodmember存取控制:private,protected,public(C++與Java寫法不同)Constructor?Destructor?DefaultConstructor?…Java沒有Destructor,但有finalize函數76Structvs.Class(1/2)#include<iostream.h>classStudent{//假设改為structStudent{…?longsid;//defaultisprivateforclass};//defaultispublicforstructintmain(){Studentx;x.sid=123;//compile錯,accessnotallowedcout<<"=="<<x.sid<<endl;//compile錯return0;}假设改為structStudent則變沒錯!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,透過publicfunctionsetId()

cout<<"=="<<x.showNumber()<<endl;//OKreturn0;}78Classvs.ObjectObjectisaninstanceofsomeclassintx;floatyy;Object(物件,個體,東西)--就是以前的變數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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论