或物件所属的空间名称.ppt
Object oriented programminglWhat is Class?What is Object?-From object-oriented point of view-Class is a user-defined data type which contains relevant data and functions-Object is a variable declared under some class data type-From philosophy concept-Class is an abstract concept that describes the attributes of a collection of objects 1From C to C+lNamespace-變數、函數、或物件所屬的空間名稱,在不同的namespace中可使用相同的變數名稱。-std:C+所有系統提供的函數所屬的namespace-avoid conflict of variable names in the different class libraries2namespace example/This program outputs the message/C+:one small step for the program,/one giant leap for the programmer/to the screen#include using namespace std;int main()cout C+:one small step for the program,n one giant leap for the programmer n;return 0;compare to C:#include main()printf(“.”);without namespace3namespaceslcreate namespace-examples:namespace mfc int inflag;void g(int);namespace owl int inflag;4namespaceluse variables in a namespace-use scope resolution operator :-e.g.mfc:inflag=3;owl:inflg=-823;cout x;cin len;cout x;cout x len;cout x len;6C+Input/Outputlexample#include using namespace std;int main()int id;float av;cout id av;cout “Id:”id n “Average:”av n;return 0;Enter the id and the average:900038 90.8Id:900038 Average:90.8 7C+Input OutputlManipulators-for the format of I/O-set width to n:setw(n)for(i=1;i=1000;i*=10)cout setw(6)i n;1 10 100 1000 8manipulatorslendl:end of line,write new line-e.g.int i=4,j=6,k=8;char c=!;cout i c endl j c n k c endl;4!6!8!9manipulatorsloct(octal),hex(hexadecimal),dec(decimal)-e.g.int i=91;cout “i=“i “(decimal)n”;cout “i=“oct i “(octal)n”;cout “i=“hex i “(hexadecimal)n”;cout “i=“dec i “(decimal)n”;i=91(decimal)i=133(octal)i=5b(hexadecimal)i=91(decimal)10manipulators llisted in chap.14-9-dec,endl,fixed,flush,hex,left,oct,right,scientific,setfill(c),setprecision(n),setw(n),showpoint,noshowpoint,showpos,noshowpos,skipws,noskipws,ws-11manipulatorslsetfill,setprecision-e.g.float a=1.05,b=10.15,c=200.87;cout setfill()setprecision(2);cout setw(10)a n;cout setw(10)b n;cout setw(10)c n;*1.05 *10.15 *200.87 12files(example)#include using namespace std;const int cutoff=6000;const float rate1=0.3;const float rate2=0.6;int main()ifstream infile;ofstream outfile;int income,tax;infile.open(income.txt);outfile.open(tax.txt);while(infile income)if(income cutoff)tax=rate1*income;elsetax=rate2*income;outfileIncome=income greenbacks n Tax=tax greenbacks n;infile.close();outfile.close();return 0;13files(example cont.)input file“income.txt”2214 10500 31010result:output file“tax.txt”Income=2214 greenbacks Tax=664 greenbacks Income=10500 greenbacks Tax=6299 greenba cks Income=31010 greenbacks Income=18605 greenbacks14filesltesting whether files are open-file object converts to true if open successfully,otherwise converts to false-e.g.ifstream infile;ifstream.open(“scores.dat”);if(infile)/if open sucessfullyorif(!infile)/if fail to open the file 15files-e.g.ifstream infile;infile.open(“scores.dat”);if(!infile)cerr “Unable to open scores.datn”;exit(0);16C+featureslbool data type-values:true(1)or false(0)-manipulators:boolalpha,noboolalpha(default)-e.g.bool flag;flag=(3 5);cout flag n;cout boolalpha flag n;1 true 17the type stringlstring initialization-e.g.#include string s1;string s2=“Bravo”;string s3=s2;string s4(10,x);cout s1 n;cout s2 n;cout s4 n;Bravo xxxxxxxxxx 18the type stringlC-style string(end with a null char 0)char mystring=“a string”;orchar mystring =“a string”;printf(“%sn”,mystring);char mystring9-the null character 0 is added by the C compiler automatically a s t r i n g 0 19the type stringlstring lengthstring s=“Ed Wood”;cout “Length=“s.length()n;linput a string-separate by space or new linecout s;cout s;Length=7 Ed Wood Ed 20getline function example(copy file)#include#include#include using namespace std;int main()string buff;ifstream infile;ofstream outfile;cout buff;infile.open(buff.c_str();cout buff;outfile.open(buff.c_str();while(getline(inflie,buff)outfile buff“nn”;infile.close();outfile.close();return 0;21the type stringlinput a line of string from cinstirng s;getline(cin,s);lconcatenation of stringstring s1=“Atlas”,s2=“King”,s3;s3=s1+s2;cout s1 n;cout s2 n;cout s3 n;Atlas King Atlas King 22the type stringlremove a substring-s.erase(position,length);-e.g.string s=“Ray Dennis Steckler”;s.erase(4,7);cout s n;Ray Steckler 23the type stringlinsert a string-s.insert(position,str2);lreplace a substring-s.replace(startpos,length,str2);lswap strings-s1.swap(s2);lextract a substring-s.substr(position,length)24the type stringl operatorstring s=“Nan”cout s1;n;s0=J;cout s n;lsearch a substring-s1.find(s2,position);lcompare strings-=,!=,=a Jan 25functionslreference variables-provides an alternative name for storage-e.g.memoryint x;int&ref=x;x refx=3;cout ref;326functionslcall by value(default in C)-pass values to the called functionlcall by reference-pass addresses to the called function-provided in C+,but not in C-e.g.void swap(int&,int&);27call by reference#include using namespace std;void swap(int&,int&);int main()int i=7,j=-3;swap(i,j);cout “i=“i n “j=“j n;return 0;void swap(int&a,int&b)int t;t=a;a=b;b=t;pass address of i,j to a,b main()swap()ti aj b 7 -3 i=-3 j=7 28call by reference in C(use pointer)#include void swap(int*,int*);/function prototypemain()int i=7,j=-3;swap(&i,&j);/passing addresses of i and j printf(“i=%d j=%d”,i,j);void swap(int*a,int*b)/use pointers parameters insteadint t;/of reference variablest=*a;*a=*b;*b=t;/use pointers to reference the /values in main function29functionsloverloading functions-functions can have the same name,but-function signatures need to be distinct-function name,and-number,data type,and order of it arguments-e.g.void print(int a);void print(double a);/o.k.void print(int a,int b);/o.k.int print(int a);/wrong!,return type is not part of signatures30functionsldefault arguments-all the parameters without default values must come first in the parameter list.-better to specify in the prototype,e.g.void f(int val,float s=12.6,char t=n,string msg=“Error”);-valid invocationf(14,48.3,t,“ok”);/s=48.3,t=t,msg=“ok”f(14,48.3);/s=48.3,t=n,msg=“Error”f(14);/s=12.6,t=n,msg=“Error”31functionsloverloading functions-functions can have the same name,but-function signatures need to be distinct-function name-number,data type,and order of it arguments-e.g.void print(int a);void print(double a);/o.k.void print(int a,int b);/o.k.int print(int a);/wrong!return type is not part of signatures32overloading functions#include#include void print(int a);void print(double a);int main()int x=8;double y=8.0;print(x);print(y);return 0;void print(int a)cout a n;void print(double a)cout showpoint a n;8 8.000 33dynamic(vs.static)allocationldynamic allocation-pointer_var=new data-type;/single data-pointer_var=new data-typesize;/array-e.g.int*int_ptr;int_ptr=new int;ptr int*ptr;ptr=new int100;ptr0 ptr1 ptr9934dynamic allocationldelete,delete-free storage allocated by new or new typesize-e.g.delete int_ptr;delete ptr;llinked list example name next start “林旺”“馬蘭”“阿美”0 35dynamic allocation#include using namespace std;struct Elephant string name;Elephant*next;void print_elephants(const Elephant*ptr);Elephant*get_elephants();void free_list(const Elephant*ptr);int main()Elephant*start;start=get_elephants();print_elephants(start);free_list(start);return 0;36dynamic allocationElephant*get_elephants()Elephant*current,*first;int response;current=first=new Elephant;cout current-name;cout response;/Add Elephants to list until user signals halt.while(response=1)current=current-next =new Elephant;cout current-name;cout response;current-next=0;return first;37dynamic allocationvoid print_elephants(const Elephant*ptr)int count=1;cout n n n;while(ptr!=0)cout Elephant number“count+is name next;void free_list(const Elephant*ptr)const Elephant*temp_ptr;while(ptr!=0)temp_ptr=ptr-next;delete ptr;ptr=temp_ptr;38dynamic allocationstruct Elephant string name;Elephant*next;first current currentname currentnextElephant*start;Elephant*current,*first;current=first=new Elephant;current=current-next =new Elephant;39exception handlingltry-throw-catch clausetry /regular statements throw an_exception;catch(exception1)/exception handlerscatch(exception2)40exception handlinglexampleint*ptr;try ptr=new int;/throw bad_alloc exception if new failure catch(bad_alloc)cerr “new:unable to allocate storage!n”;exit(0);41Programming homework(1).執行p.36的程式,輸入至少10隻象的名字。(2).加入一新的function名為reverse_elephant至p.36程式中,其function prototype如下:Elephant*reverse_elephant(Elephant*start);此function的功能在於建立一新linked list,將原以start為起點的linked list中的資料做反向連結,然後傳回此新的linked list的起始位置的pointer值;並在main function中至少重複呼叫reverse_function兩次,用以驗證你的程式的正確性。例如:原:start 經reverse_elephant後:rstart elp1 elp2 elpn 0 elpn elp2 elp1 0 42