版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
ObjectorientedprogrammingWhatisClass?WhatisObject?Fromobject-orientedpointofviewClassisauser-defineddatatypewhichcontainsrelevantdataandfunctionsObjectisavariabledeclaredundersomeclassdatatypeFromphilosophyconceptClassisanabstractconceptthatdescribestheattributesofacollectionofobjects1FromCtoC++Namespace變數、函數、或物件所屬旳空間名稱,在不同旳namespace中可使用相同旳變數名稱。std:C++全部系統提供旳函數所屬旳namespaceavoidconflictofvariablenamesinthedifferentclasslibraries2namespaceexample//Thisprogramoutputsthemessage////C++:onesmallstepfortheprogram,//onegiantleapfortheprogrammer////tothescreen#include<iostream>usingnamespacestd;intmain(){cout<<"C++:onesmallstepfortheprogram,\n"<<"onegiantleapfortheprogrammer\n";return0;}comparetoC:#include<stdio.h>main(){
printf(“….”);withoutnamespace3namespacescreatenamespaceexamples: namespacemfc{ intinflag; voidg(int);…}namespaceowl{ intinflag; …}4namespaceusevariablesinanamespaceusescoperesolutionoperator::e.g.mfc::inflag=3;owl::inflg=-823;cout<<mfc::inflag;theusingdirectivee.g..usingnamespacemfc;inflag=3;//相當於mfc::inflag=3;owl::inflag=-823;5C++Input/OutputC++Input/Outputobjectscin standardinputcout standardoutputcerr standarderrore.g.cin>>x;cin>>len;cout<<x;cout<<len;cin>>x>>len;
cout<<x<<len;6C++Input/Outputexample#include<iostream>usingnamespacestd;intmain(){intid;floatav;cout<<“Entertheidandtheaverage:”;cin>>id>>av;cout<<“Id:”<<id<<‘\n’<<“Average:”<<av<<‘\n’;return0;}Entertheidandtheaverage:90003890.8Id:900038Average:90.8
7C++InputOutputManipulatorsfortheformatofI/Osetwidthton:setw(n)for(i=1;i<=1000;i*=10)cout<<setw(6)<<i<<‘\n’;11010010008manipulatorsendl:endofline,writenewlinee.g.inti=4,j=6,k=8;charc=‘!’;cout<<i<<c<<endl<<j<<c<<‘\n’ <<k<<c<<endl;4!6!8!9manipulatorsoct(octal),hex(hexadecimal),dec(decimal)e.g.inti=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)10manipulatorslistedinchap.14-9dec,endl,fixed,flush,hex,left,oct,right,scientific,setfill(c),setprecision(n),setw(n),showpoint,noshowpoint,showpos,noshowpos,skipws,noskipws,ws
11manipulatorssetfill,setprecisione.g.floata=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.8712files(example)#include<fstream>usingnamespacestd;constintcutoff=6000;constfloatrate1=0.3;constfloatrate2=0.6;intmain(){ifstreaminfile;ofstreamoutfile;intincome,tax;infile.open("income.txt");outfile.open("tax.txt");while(infile>>income){if(income<cutoff)tax=rate1*income;elsetax=rate2*income;outfile<<"Income="<<income<<"greenbacks\n"<<"Tax="<<tax<<"greenbacks\n";}infile.close();outfile.close();return0;}13files(examplecont.)inputfile“income.txt”22141050031010result:outputfile“tax.txt”Income=2214greenbacksTax=664greenbacksIncome=10500greenbacksTax=6299greenbacksIncome=31010greenbacksIncome=18605greenbacks14filestestingwhetherfilesareopenfileobjectconvertsto‘true’ifopensuccessfully,otherwiseconvertsto‘falsee.g.ifstreaminfile;ifstream.open(“scores.dat”);…if(infile){…}//ifopensucessfullyorif(!infile){…}//iffailtoopenthefile15filese.g..ifstreaminfile;infile.open(“scores.dat”);if(!infile){cerr<<“Unabletoopenscores.dat\n”;exit(0);}16C++featuresbooldatatypevalues:true(1)orfalse(0)manipulators:boolalpha,noboolalpha(default)e.g.boolflag;flag=(3<5);cout<<flag<<‘\n’;cout<<boolalpha<<flag<<‘\n’;1true17thetypestringstringinitializatione.g.#include<string>strings1;strings2=“Bravo”;strings3=s2;strings4(10,’x’);cout<<s1<<‘\n’;cout<<s2<<‘\n’;cout<<s4<<‘\n’;Bravoxxxxxxxxxx
18thetypestringC-stylestring(endwithanullchar‘\0’)charmystring=“astring”;orcharmystring[]=“astring”;printf(“%s\n”,mystring);charmystring[9]thenullcharacter‘\0’isaddedbytheCcompilerautomaticallyastring\0
19thetypestringstringlengthstrings=“EdWood”;cout<<“Length=“<<s.length()<<‘\n’;inputastringseparatebyspaceornewlinecout<<“Enterastring:”;cin>>s;cout<<s;Length=7
EdWoodEd20getlinefunctionexample(copyfile)#include<iostream>#include<fstream>#include<string>usingnamespacestd;intmain(){stringbuff;ifstreaminfile;ofstreamoutfile;cout<<“Inputfilename:”;cin>>buff;infile.open(buff.c_str());cout<<“Outputfilename:”;cin>>buff;outfile.open(buff.c_str());while(getline(inflie,buff))outfile<<buff<<“\n\n”;infile.close();outfile.close();return0;}21thetypestringinputalineofstringfromcinstirngs;getline(cin,s);concatenationofstringstrings1=“Atlas”,s2=“King”,s3;s3=s1+s2;cout<<s1<<‘\n’;cout<<s2<<‘\n’;cout<<s3<<‘\n’;AtlasKingAtlasKing22thetypestringremoveasubstrings.erase(position,length);e.g.strings=“RayDennisSteckler”;s.erase(4,7);cout<<s<<‘\n’;RaySteckler23thetypestringinsertastrings.insert(position,str2);replaceasubstrings.replace(startpos,length,str2);swapstringss1.swap(s2);extractasubstrings.substr(position,length)24thetypestring[]operatorstrings=“Nan”cout<<s[1];<<‘\n’;s[0]=‘J’;cout<<s<<‘\n’;searchasubstrings1.find(s2,position);comparestrings==,!=,<,>,<=,>=aJan25functionsreferencevariablesprovidesanalternativenameforstoragee.g.memoryintx;int&ref=x;xrefx=3;cout<<ref;326functionscallbyvalue(defaultinC)passvaluestothecalledfunctioncallbyreferencepassaddressestothecalledfunctionprovidedinC++,butnotinCe.g.voidswap(int&,int&);27callbyreference#include<iostream>usingnamespacestd;voidswap(int&,int&);intmain(){inti=7,j=-3;swap(i,j);cout<<“i=“<<i<<‘\n’<<“j=“<<j<<‘\n’;return0;}voidswap(int&a,int&b){intt;t=a;a=b;b=t;}
passaddressofi,jtoa,b
main()
swap()tiajb7-3
i=-3j=728callbyreferenceinC(usepointer)#include<stdio.h>voidswap(int*,int*);//functionprototypemain(){inti=7,j=-3;swap(&i,&j);//passingaddressesofiandjprintf(“i=%dj=%d”,i,j);}voidswap(int*a,int*b){//usepointersparametersinsteadintt;//ofreferencevariablest=*a;*a=*b;*b=t;//usepointerstoreferencethe}//valuesinmainfunction29functionsoverloadingfunctionsfunctionscanhavethesamename,butfunctionsignaturesneedtobedistinctfunctionname,andnumber,datatype,andorderofitargumentse.g.voidprint(inta);voidprint(doublea);//o.k.voidprint(inta,intb);//o.k.intprint(inta);//wrong!,returntypeisnotpartofsignatures30functionsdefaultargumentsalltheparameterswithoutdefaultvaluesmustcomefirstintheparameterlist.bettertospecifyintheprototype,e.g.voidf(intval,floats=12.6,chart=‘\n’,stringmsg=“Error”);validinvocationf(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”31functionsoverloadingfunctionsfunctionscanhavethesamename,butfunctionsignaturesneedtobedistinctfunctionnamenumber,datatype,andorderofitargumentse.g.voidprint(inta);voidprint(doublea);//o.k.voidprint(inta,intb);//o.k.intprint(inta);//wrong!returntypeisnotpartofsignatures32overloadingfunctions#include<iostream>#include<iomanip>voidprint(inta);voidprint(doublea);intmain(){intx=8;doubley=8.0;print(x);print(y);return0;}voidprint(inta){cout<<a<<‘\n’;}voidprint(doublea){cout<<showpoint<<a<<‘\n’;}88.00033dynamic(vs.static)allocationdynamicallocationpointer_var=newdata-type;//singledatapointer_var=newdata-type[size];//arraye.g.int*int_ptr;
int_ptr=newint;ptrint*ptr;ptr=newint[100];ptr[0]ptr[1]…ptr[99]…34dynamicallocationdelete,delete[]freestorageallocatedbynewornewtype[size]e.g.deleteint_ptr;delete[]ptr;linkedlistexamplenamenextstart‧‧‧
“林旺”“馬蘭”“阿美”035dynamicallocation#include<string>usingnamespacestd;structElephant{stringname;Elephant*next;};voidprint_elephants(constElephant*ptr);Elephant*get_elephants();voidfree_list(constElephant*ptr);intmain(){Elephant*start;start=get_elephants();print_elephants(start);free_list(start);return0;}36dynamicallocationElephant*get_elephants(){Elephant*current,*first;intresponse;current=first=newElephant;cout<<"\nNAME:";cin>>current->name;cout<<"\nAddanother?(1==yes,0==no):";cin>>response;//AddElephantstolistuntilusersignalshalt.while(response==1){
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 地理东南亚考试题及答案
- 邢台电器保护器项目可行性研究报告
- 重点项目-金属紧固件滑轮项目可行性研究报告
- 门诊部设置可行性研究报告5范例
- 防水设施材料项目可行性研究报告申请报告
- 驱动器项目可行性研究报告
- 2025年安徽省电子信息行业职业技能竞赛(人工智能训练师)备赛试题库(含答案)
- 广西中考物理5年(2021-2025)真题分类汇编:专题05 机械运动与质量与密度(解析版)
- 临床医院“互联网+护理服务”管理制度
- 2025年中级注册安全工程师之安全生产法及相关法律知识提升训练试卷A卷附答案
- GB/T 3830-2024软聚氯乙烯压延薄膜和片材
- 食品安全的规章制度目录清单
- 小学生心理健康帮扶计划及措施
- TCI 368-2024 供电服务客服调度管理规范
- HG∕T 2454-2014 溶剂型聚氨酯涂料(双组份)
- 2023-2024学年全国小学六年级上英语人教版期中试卷(含答案解析)
- 译林版二年级上册英语期中卷(含听力材料)
- 玉米脱粒机项目计划方案
- DZ∕T 0283-2015 地面沉降调查与监测规范(正式版)
- 明清古家具鉴赏 知到智慧树网课答案
- 大学生职业规划大赛成长赛道参赛作品
评论
0/150
提交评论