版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter1
AnswerstoExercisesProgrammingisplanningtheperformanceofataskoranevent.Algorithmisastep-by-stepprocedureforsolvingaprobleminafiniteamountoftime.Object-orientedprogramming,shortenedtoOOP,isaprogrammingparadigmthatusestheconceptof"objects"–datastructuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions–todesignapplicationsandcomputerprograms.Thenameofthedatastructureweusediscalledobjects.Thecomponentsofthisdatastructurecontaindataandmethods.ThecharacteristicsofOOPincludesdataabstraction,informationhiding,encapsulation,inheritanceandpolymorphism.Thedifferencesbetweenstructuredprogrammingandobject-orientedprogrammingareshowninthefollowingtable.StructuredProgrammingObject-OrientedProgrammingStructuredProgrammingisdesignedwhichfocusesonprocess/logicalstructureandthendatarequiredforthatprocess.ObjectOrientedProgrammingisdesignedwhichfocusesondata.structuredprogrammingfollowstop-downapproachObjectorientedprogrammingfollowsbottom-upapproachStructuredProgrammingisalsoknownasModularProgrammingandasubsetofproceduralprogramminglanguage.ObjectOrientedProgrammingsupportsinheritance,encapsulation,abstraction,polymorphism,etc.InStructuredProgramming,programsaredividedintosmallselfcontainedfunctions.InObjectOrientedProgramming,programsaredividedintosmallentitiescalledobjects.StructuredProgrammingislesssecureasthereisnowayofdatahiding.ObjectOrientedProgrammingismoresecureashavingdatahidingfeature.StructuredProgrammingcansolvemoderatelycomplexprograms.ObjectOrientedProgrammingcansolveanycomplexprograms.StructuredProgrammingprovideslessreusability,morefunctiondependency.ObjectOrientedProgrammingprovidesmorereusability,lessfunctiondependency.Lessabstractionandlessflexibility.Lessabstractionandlessflexibility.Whydoweneedobject-orientedprogramming?(selfanswer)Chapter21(1)b(2)d(3)c(4)a(5)a(6)a2.#include<iostream>usingnamespacestd;int&put(intn); //putvalueintothearrayintget(intn); //obtainavaluefromthearrayintvals[10];interror=-1;voidmain(){put(0)=10; //putvalueintothearrayput(1)=20;put(2)=30;cout<<get(0)<<endl;cout<<get(1)<<endl;cout<<get(2)<<endl;put(12)=1; //outofboundcout<<get(12)<<endl;}int&put(intn){if(n<10)returnvals[n];else{ cout<<"Outofbound!\n";returnerror;}}intget(intn){if(n<10)returnvals[n];}3.(1)10;10
else
returnerror;004BF928:004BF928(2)5;98.3(3)InfunctionTest,thevariableequal525AfterthefirstcallofTest,thevariablesequal514InfunctionTest,thevariableequal525AfterthesecondcallofTest,thevariablesequal5224.#include<iostream>usingnamespacestd;voidswap(int&,int&,double*,double*);intmain(){intm,n;doubles,t;cout<<"Pleaseentertwointegers.\n";cin>>m>>n;cout<<"Pleaseentertwodoubllefloating-pointnumbers.\n";cin>>s>>t;swap(m,n,&s,&t);cout<<"Twointegersmandn:"<<m<<","<<n<<endl;cout<<"Twodoublefloating-pointnumberssandt:"<<s<<","<<t<<endl;return0;}voidswap(int&i,int&j,double*a,double*b){intiTemp=i;i=j;j=iTemp;doubledTemp=*a;*a=*b;*b=dTemp;}5.#include<iostream>usingnamespacestd;intdisplay(int);doubledisplay(double);chardisplay(char);intmain(){intn;doubled;charch;cout<<"Enteraninteger,adoublefloating-pointnumber,acharacter:\n";cin>>n>>d>>ch;cout<<"Displayaninteger:"<<display(n)<<endl;cout<<"Displayadoublefloating-pointnumber:"<<display(d)<<endl;}
cout<<"Displayacharacter:"<<display(ch)<<endl;return0;intdisplay(intk){returnk;}doubledisplay(doubles){returns;}chardisplay(charc){returnc;}6.#include<iostream>usingnamespacestd;voidreverse(int&);intmain(){intn;cout<<"Enteranintegerwithmorethan4digits.\n";cin>>n;reverse(n);cout<<"Theintegeris"<<n<<endl;return0;}voidreverse(int&m){intnewNum=0;while(m>0){newNum =newNum*10+m%10;m/=10;}m=newNum;}7.#include<iostream>usingnamespacestd;intqualityPoints(floata);intmain(){floataverage;cout<<"Enterastudent'saverage.\n";cin>>average;cout<<"Hisqualitypointis"<<qualityPoints(average)<<endl;return0;}intqualityPoints(floata){intpoint=0;if(a>=90&&a<=100)point=4;if(a>=80&&a<90)point=3;if(a>=70&&a<80)point=2;if(a>=60&&a<70)point=1;returnpoint;}8.#include<iostream>#include<ctime>usingnamespacestd;constintARRAY_SIZE=10;voidfind(int[],int&,int&);intmain(){intarray[ARRAY_SIZE];srand(time(0));for(inti=0;i<ARRAY_SIZE;i++)array[i]=rand()%99+10;for(inti=0;i<ARRAY_SIZE;i++)cout<<array[i]<<",";cout<<endl;intmaxV,minV;find(array,maxV,minV);cout<<"Themaxvalueis"<<maxV<<endl;cout<<"Theminvalueis"<<minV<<endl;return0;}voidfind(intarr[],int&max,int&min){max=min=arr[0];for(inti=0;i<ARRAY_SIZE;i++){if(max<arr[i])max=arr[i];if(min>arr[i])min=arr[i];}}9.#include<iostream>usingnamespacestd;intintegerPower(int,int);intmain(){intbase,exponent;cout<<"Enterabase.\n";cin>>base;do{cout<<"Entertheexponentofthebase(>0).\n";cin>>exponent;}while(exponent<=0);cout<<"Thevalueofbase"<<base<<"withexponent"<<exponent<<"is"<<integerPower(base,exponent)<<endl;return0;}intintegerPower(intbas,intexp){inttotalV=1;for(inti=0;i<exp;i++)totalV*=bas;returntotalV;}(omitted)(omitted)(omitted)(omitted)(omitted)15.#include<iostream>#include<string>#include<ctime>usingnamespacestd;intnumber;intguess;;stringresult;intcount=0;voidgetRandomNum(){srand(time(0));number=rand()%1001;count=0;}voidGuess(){while(guess!=number){cout<<"Ihaveanumberbetween1and1000.Canyouguessmynumber?Pleasetypeyournumber:\n";cin>>guess;if(guess>number)result="Toohigh.Tryagain..\n";elseif(guess==number)result="Bingo!Youguessedthenumber.\n";elseresult="Toolow.Tryagain...\n";count++;cout<<result<<endl;}}intmain(){getRandomNum();while(1){Guess();if(count<=5)cout<<"Youknowthesecret?\n";elseif(count<=10&&count>5)cout<<"Yougotthelucky!\n";elsecout<<"Youshouldbeabletobebetter.\n";cout<<"Thisnumberis"<<number<<endl;cout<<"Doyoucontinuetoplay?Ifyes,presstheYkey;otherwisepressanykey\n";charch;ch=cin.get();ch=cin.get();if(ch=='Y')getRandomNum();else}
break;return0;}Chapter31.(1)T(2)T(3)F(4)F(5)F(6)T(7)F(8)T(9)T(10)T(11)F(12)T(13)F(14)F(15)T(16)F(17)T(18)T(19)T(20)F(21)F(22)F(23)T(24)F2.(1)classAA{public:voidAA(int,int); X correct: AA(int,int)intsum();private:intx=0; X correct:intx;inty;};(2)classBB {
public:BB(int,int);print(); error correct: voidprint();private:intx,y;} error correct: };(3)classCC {};
public:CC();CC(int,int);private:intx,y;intmain(){ CCc1(4); error correct:CC c1;or CCc1(4,10);CCc2(4,5);CCc3;cout<<c2.x<<c2.y<<endl; error correct:deletethisstatementreturn0;}3.classPointhas4members.classPointhas2privatemembers.classPointhas2constructors(4)Point::Point(){ cout<<"Defaultconstructor.\n";x=y=0;}(5)Point::Point(intxx,intyy){ cout<<"Constructor.\n";x=xx;y=yy;}(6)voidPoint::move(intnewX,intnewY){}(7)
if(x!=newX||y!=newY){ x=newX;y=newY; }voidPoint::print(){cout<<x<<","<<y<<endl;}(8)intmain(){Pointp1,p2(12,25);p1.print();p2.print();p2.move(30,10);p2.print();return0;}4.File:3-4.hclassWord{public:Word();Word(char*w);voidaddMeanings();char*getMeanings(intn);intgetMeaningsNum();voidprint();char*getWord();~Word();private:char*name;char*meanings[20];intmeaningsNum;};File:3-4.cpp#include"3-4.h"#include<iostream>#include<string>usingnamespacestd;Word::Word(){}Word::Word(char*w){name=newchar[strlen(w)+1];strcpy(name,w);cout<<"Creatingtheword"<<name<<endl;meaningsNum=0;}Word::~Word(){cout<<"Destroyingtheword"<<name<<endl;deletename; //refto.Section4.4for(inti=0;i<meaningsNum;i++)delete[]meanings[i];}voidWord::addMeanings(){char*s=newchar[50];cout<<"Entertheword'smeaning\n";cin.getline(s,50);meanings[meaningsNum]=newchar[strlen(s)+1];strcpy(meanings[meaningsNum],s);meaningsNum++;deletes;}char*Word::getMeanings(intn){if(n>=0&&n<meaningsNum)returnmeanings[n];else}
return"Failtogetaword'smeaning";intWord::getMeaningsNum(){returnmeaningsNum;}voidWord::print(){cout<<"Word:"<<name<<endl;cout<<"Meanings:\n";for(inti=0;i<meaningsNum;i++)cout<<i<<":"<<meanings[i]<<endl;}char*Word::getWord(){ returnname; }intmain(){Wordword1("Class");word1.addMeanings();word1.addMeanings();cout<<"Word"<<word1.getWord()<<"has"<<word1.getMeaningsNum()<<"meanings.\n";cout<<"Listallmeaningsofword"<<word1.getWord()<<endl;for(inti=0;i<word1.getMeaningsNum();i++)cout<<i<<":"<<word1.getMeanings(i)<<endl;Wordword2("Object");word2.addMeanings();word2.addMeanings();cout<<"Word"<<word2.getWord()<<"has"<<word1.getMeaningsNum()<<"meanings.\n";cout<<"Listallmeaningsofword"<<word2.getWord()<<endl;for(inti=0;i<word2.getMeaningsNum();i++)cout<<i<<":"<<word2.getMeanings(i)<<endl;return0;}5.#include<iostream>usingnamespacestd;classTimeDemo{public:TimeDemo(int=0,int=0,int=0);voidsetValue(int,int,int);voidprint();private:intsecond,minute,hour;};TimeDemo::TimeDemo(ints,intm,inth){if((h<=24&&h>0)&&(m<60&&m>0)&&(s<60&&s>0)){}else{}}
second=s;minute=m;hour=h;cout<<"failtime\n";voidTimeDemo::setValue(ints,intm,inth){if((h<=24&&h>0)&&(m<60&&m>0)&&(s<60&&s>0)){}else{}}
second=s;minute=m;hour=h;cout<<"Failtime\n";voidTimeDemo::print(){cout<<"Pleasechooseoutputformat:0-12hours;1-24hours.\n";intn;cin>>n;if(!n){if(hour>12)hour-=12;}cout<<hour<<":"<<minute<<":"<<second<<endl;}voidmain(){TimeDemotime1(23,45,20);time1.setValue(12,55,23);time1.print();}6.File:3-6.hclassRectangle{public:Rectangle(int=1,int=1);intperimeter();intarea();voidsetValue();intgetWidth();intgetLength();private:intlength,width;};File:3-6.cpp#include"3-6.h"#include<iostream>usingnamespacestd;Rectangle::Rectangle(intl,intw){length=l;width=w;}intRectangle::perimeter(){ return2*(length+width); }intRectangle::area(){ returnlength*width; }voidRectangle::setValue(){cout<<"Enteranewlength(>0)andwidth(>0)oftherectangle.\n";while(cin>>length>>width,length<=0||width<=0){cout<<"Faillengthorwidth!\n";cout<<"Enterthelength(>0)andwidth(>0)oftherectangle.\n";}}intRectangle::getLength(){ returnlength; }intRectangle::getWidth(){ returnwidth;}intmain(){Rectanglerect1;cout<<"Therectangle'slengthandwidthare"<<rect1.getLength()<<"and"<<rect1.getWidth()<<endl;cout<<"Therectangle'sperimeterandareaare"<<rect1.perimeter()<<"and"<<rect1.area()<<endl;rect1.setValue();cout<<"Therectangle'slengthandwidthare"<<rect1.getLength()<<"and"<<rect1.getWidth()<<endl;cout<<"Therectangle'sperimeterandareaare"<<rect1.perimeter()<<"and"<<rect1.area()<<endl;cout<<endl;Rectanglerect2(23,25);cout<<"Therectangle'slengthandwidthare"<<rect1.getLength()<<"and"<<rect1.getWidth()<<endl;cout<<"Therectangle'sperimeterandareaare"<<rect1.perimeter()<<"and"<<rect1.area()<<endl;rect1.setValue();cout<<"Therectangle'slengthandwidthare"<<rect1.getLength()<<"and"<<rect1.getWidth()<<endl;cout<<"Therectangle'sperimeterandareaare"<<rect1.perimeter()<<"and"<<rect1.area()<<endl;return0;}Chapter4Markthefollowingstatementsastrueorfalseandgivereasons.(1)T(2)T(3)T(4)F(5)F(6)T(7)T(8)F(9)T(10)T(11)T(12)FFindtheerror(s)ineachofthefollowingandexplainhowtocorrectit.(1)classAA{private:inta;intb;public:AA(intx){a=0;b=x;)voidprint()const{ b++; error change: b; nochangedatamemberinconstfunctioncout<<b;}};voidmain(){ AA aa; error change: AAaa(10);aa.print();cout<<AA::a; errorchange:deletethisline,noaccessprivatemembera}(2)classA{intx;Dated;staticintyopublic:voidA(inta) error change: A(inta,intd,intm,inty):d(d,m,y){x=a;d(a,a,a) error change:deletethisline.Objectmemberisinitializedbyinitializery=0; error change:deletethisline.Staticdataisinitializedoutsidetheclass}};voidmain(){ Aaa; error change: Aaa(10,20,8,2019);cout<<aa.y<<endl; error change:noaccessprivatedatamemberyAbb(10); error change: A bb(10,29,12,2017);cout<<bb.y<<endl; error change:noaccessprivatedatamembery}3.Writeouttheoutputofthefollowingcodes:Output:constructingdefaultAconstructingdefaultBconstrctingAconstructingBdestructingBdestructingAdestructingBdestructingAOutput:100Output:n=2,sum=2n=3,sum=5n=5,sum=10Output:CreatinganobjectCopyanobjectCallingtheincrementfunctionCopyanobjectCallingtheincrementfunctionCopyanobjectCallingtheincrementfunctionmyCount.countis0timesis0ifthestatementvoidincrement(Countc,inttimes)ischangedtovoidincrement(Count&c,int×),Output:CreatinganobjectCopyanobjectCallingtheincrementfunctionCopyanobjectCallingtheincrementfunctionCopyanobjectCallingtheincrementfunctionmyCount.countis0timesis34.classCube{public:Cube();Cube(int,int,int);Cube(constCube&);intvolume()const;voidprint()const;voidmove();voidmodify();~Cube();private:intlength,width,height;intx,y,z;};Cube::Cube(){x=y=z=0;length=width=height=1;cout<<"Creatingadefaultobject...\n";}Cube::Cube(intl,intw,inth){x=y=z=0;length=l;width=w;height=h;cout<<"Creatinganobject...\n";}Cube::Cube(constCube&c){x=c.x;y=c.y;z=c.z;length=c.length;width=c.width;height=c.height;cout<<"Creatinganobject.fromanexistingobject...\n";}Cube::~Cube(){cout<<"Destroyinganobject...\n";}voidCube::print()const{cout<<"Displaythecube'slocationis("<<x<<","<<y<<","<<z<<")\n";cout<<"Displaythecube'sdemensionais"<<length<<","<<width<<","<<height<<".\n";}intCube::volume()const{returnlength*width*height;}voidCube::move(){cout<<"Enteranewlocation(x,y,z).\n";cin>>x>>y>>z;}voidCube::modify(){intn;cout<<"Enteravalue:0--modifyinglocation;1--modifyingdemension.\n";cin>>n;if(n){}else{
cout<<"Enteranewdemension.\n";cin>>length>>width>>height;cout<<"Enteranewlocation(x,y,z).\n";cin>>x>>y>>z;}}intmain(){Cubecube1;cube1.print();cout<<"Thiscube'svolumeis"<<cube1.volume()<<endl;cube1.move();cube1.print();cube1.modify();cube1.print();Cubecube2(3,4,5);cube2.print();cout<<"Thiscube'svolumeis"<<cube2.volume()<<endl;Cubecube3=cube2;cube3.print();cout<<"Thiscube'svolumeis"<<cube3.volume()<<endl;Cubecube4(cube1);cube4.print();cout<<"Thiscube'svolumeis"<<cube4.volume()<<endl;return0;}5.#include<iostream>#include<string>#include<iomanip>usingnamespacestd;classemployee{public:voidgetdata();voidputdate()const;private:stringname;longnumber;};voidemployee::getdata(){cout<<"Enteranexployee'sname:\n";cin>>name;cout<<"Enteranexployee'snumber.\n";cin>>number;}voidemployee::putdate()const{cout<<setw(10)<<name<<setw(10)<<number<<endl;}intmain(){intemployeeNum;cout<<"Enterthenumberoftheemployee.\n";cin>>employeeNum;employee*em=newemployee[employeeNum];for(inti=0;i<employeeNum;i++)em[i].getdata();cout<<"Listofallemployee.\n";cout<<setw(10)<<"name"<<setw(10)<<"number"<<endl;for(inti=0;i<employeeNum;i++)em[i].putdate();delete[]em;return0;}6.File:4-6.hconstintMAX_MREANINGS_NUM=6;classWord{public:Word(); //defaultconstructorWord(constWord&); //copyconstructorWord(char*w,char*def[]); //constructorWord©(constWord&); //copyanobjecttoanotherobjectvoidaddMeanings(); //addameaningofthewordchar*getMeanings(intn);//getameaningofthewordintgetMeaningsNum(); //getthenumberofthewordmeaningsvoidprint(); //displayallmeaningsofthewordchar*getWord(); //getaword'sname~Word();private:char*name; //word'snamechar*meanings[MAX_MREANINGS_NUM]; //allmeaningsintmeaningNum; //numberofthewordmeanings};classDictionary{public:Dictionary(intn=5); //defaultconstructorvoidaddWord(Word&w); //addawordintothedictionaryboolfindWord(char*s,int&index);//lookupawordinthedictionaryvoidgetWord(char*s); //getawordinthedictionaryvoidprint(); //displayallwordsofthedictionaryvoidprint(int); //diplayawordofthedictionary~Dictionary();private:Word*words; //objectmemberintwordNum; //thenumberofwordsintwordIndex;};File:4-6.cpp#include"4-6.h"#include<iostream>#include<string>usingnamespacestd;Word::Word(){}Word::Word(constWord&w){name=newchar[strlen()+1];strcpy(name,);meaningNum=w.meaningNum;for(inti=0;i<w.meaningNum;i++){meanings[i]=newchar[strlen(w.meanings[i])+1];strcpy(meanings[i],w.meanings[i]);}}Word::Word(char*w,char*def[]){cout<<"Creatingaword.\n";intn=strlen(w)+1;name=newchar[n];strcpy(name,w);meaningNum=0;while(def[meaningNum]){meanings[meaningNum]=newchar[strlen(def[meaningNum])+1];strcpy(meanings[meaningNum],def[meaningNum]);meaningNum++;}}Word::~Word(){cout<<"Deletingtheword"<<name<<endl;deletename;for(inti=0;i<meaningNum;i++)delete[]meanings[i];}voidWord::addMeanings(){char*s=newchar[50];cout<<"Entertheword'smeaning\n";cin.getline(s,50);cin.getline(s,50); //therecanbeablankbetweentwowordsmeanings[meaningNum]=newchar[strlen(s)+1];strcpy(meanings[meaningNum],s);meaningNum++;}char*Word::getMeanings(intn){if(n>=0&&n<meaningNum)returnmeanings[n];else}
return"Outofbound!Failtogetaword'smeaning.";intWord::getMeaningsNum(){returnmeaningNum;}voidWord::print(){cout<<"Word:"<<name<<endl;cout<<"Listallofitsmeanings.\n";for(inti=0;i<meaningNum;i++)cout<<i<<":"<<meanings[i]<<endl;}char*Word::getWord(){returnname;}Word&Word::copy(constWord&w){name=newchar[strlen()+1];strcpy(name,);meaningNum=w.meaningNum;for(inti=0;i<meaningNum;i++){meanings[i]=newchar[strlen(w.meanings[i])+1];strcpy(meanings[i],w.meanings[i]);}return*this;}Dictionary::Dictionary(intn){cout<<"Buildingadictionary.\n";wordNum=n;words=newWord[wordNum];wordIndex=0;}Dictionary::~Dictionary(){delete[]words;cout<<"Deletingthisdictionary.\n";}voidDictionary::addWord(Word&w){if(wordIndex<wordNum)words[wordIndex].copy(w);wordIndex++;}boolDictionary::findWord(char*s,int&index){boolfindFlag=false;for(inti=0;i<wordIndex;i++){char*temp=words[i].getWord();if(*temp==*s){ index=i;findFlag=true;break;}}returnfindFlag;}voidDictionary::getWord(char*s){intindex;charstr[50];if(findWord(s,index))words[index].print();else}
cout<<"Can'tfindthiswords.";voidDictionary::print(){for(inti=0;i<wordIndex;i++){cout<<"The"<<i<<"thword:\n.";words[i].print();}}voidDictionary::print(inti){words[i].print();}intmain(){char*def1[]={"班级","类","阶级",0};char*def2[]={"物品","对象","目的","障碍",0};Wordword[2]={Word("class",def1),Word("object",def2)}; //createanarrayofWordcout<<"Word'sname:"<<word[0].getWord()<<endl;cout<<"Thereare"<<word[0].getMeaningsNum()<<"meaningsofthisword."<<endl;word[0].print();intnum;cout<<"Enterthenumberofthewordmeaningyouwant.\n";cin>>num;cout<<word[0].getMeanings(num)<<endl;cout<<"Addameaningofthecurrentword.\n";word[0].addMeanings();word[0].print();Dictionarydic(2);for(inti=0;i<2;i++){dic.addWord(word[i]);}intind;if(dic.findWord("book",ind)){}else
cout<<"findit!\n";dic.print(ind);cout<<"Connotfindit!\n";dic.getWord("class");cout<<"Listallwordsinthedictionary\n";dic.print();return0;}7.#include<iostream>usingnamespacestd;doublesum=0.0;classBank{public:Bank(doubleb=0.0);frienddoubletotal(Bank&);voiddisplay()const;private:doublebalance;};Bank::Bank(doubleb){balance=b;}voidBank::display()const{cout<<"Balance="<<balance<<endl;}doubletotal(Bank&b){sum+=b.balance;returnsum;}intmain(){Bankbank1(1000.45),bank2(50000.89),bank3(300.00);total(bank1);total(bank2);cout<<"Totalofbalance:"<<total(bank3)<<endl;return0;}8.#include<iostream>#include<string>#include<cmath>usingnamespacestd;classMyInteger{public:MyInteger(int);intget()const;boolisEven()const;staticboolisEven(int);boolisEqual(constMyInteger&)const;intparseInt(conststring&);private:intvalue;};MyInteger::MyInteger(intmyint):value(myint){}intMyInteger::get()const{returnvalue;}boolMyInteger::isEven()const{returnvalue%2==0;}boolMyInteger::isEven(intn){returnn%2==0;}boolMyInteger::isEqual(constMyInteger&myint)const{returnthis->value==myint.value;}intMyInteger::parseInt(conststring&str){intj,n,sum=0;for(inti=0;i<str.length();i++){if(isdigit(str[i])){}else{}}
j=str[i]-48;n=str.length()-i-1;sum+=j*pow(10,n);cout<<"Aninvalidstring\n";exit(1);value=sum;returnvalue;}intmain(){MyIntegermyint(12);if(myint.isEven())cout<<myint.get()<<"iseven\n";elsecout<<myint.get()<<"isnoteven\n";intm=31;if(myint.isEven(m))cout<<m<<"iseven\n";elsecout<<m<<"isnoteven\n";MyIntegeryourint(20);if(myint.isEqual(yourint))cout<<"Twoobjectsareequal\n";elsecout<<"Twoobjectsareunequal\n";stringstr;cout<<"Enteradigitstring:";cin>>str;cout<<myint.parseInt(str)<<endl;return0;}Chapter51.(1)T(2)F(3)F(4)T(5)F(6)T(7)F(8)T(9)T(10)F(11)T(12)T2.Rectangle&operator++(Rectangle&r){r.setLength(r.getLength()+1);r.setWidth(r.getWidth()+1);returnr;}Rectangle&Rectangle::operator=(Rectangle&r){length=r.length;width=r.width;return*this;}Rectangleoperator+(Rectangle&r1,Rectangle&r2){}Result:
Rectangletemp;temp.length=r1.length+r2.length;temp.width=r1.width+r2.width;returntemp;constructingaRectangleobject..constructingaRectangleobject..constructingaRectangleobject..constructingaRectangleobject..length=12width=14length=13width=153.#include<iostream>#include<algorithm>usingnamespacestd;classDate{public:Date(int=2019,int=1,int=1);Date&operator++();booloperator==(constDate&);booloperator<=(constDate&);booloperator!=(constDate&);friendistream&operator>>(istream&,Date&);friendostream&operator<<(ostream&,Date&);private:intyear,month,day;boolIsRight(int,int,int);boolIsLeapYear(int);staticintdayOfMonth[13];};intDate::dayOfMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};//examinealeapyearboolDate::IsLeapYear(inty){return!(y%4)&&(y%100)||!(y%400);}//examineavaliddateboolDate::IsRight(intd,intm,inty){intmaxDay;if((y>9999)||(y<1)||(d<1)||(m<1)||(m>12))returnfalse;maxDay=31;switch(m)case4:case6:case9:case11:maxDay--;if(m==2)maxDay=IsLeapYear(y)?29:28;return(d>maxDay)?false:true;}//constructorDate::Date(inty,intm,intd){if(IsRight(d,m,y)){}else{
day=d;month=m;year=y;year=max(1,y);month=max(1,m);month=min(month,12);dayOfMonth[2]=28+IsLeapYear(year);day=max(1,d);day=min(day,dayOfMonth[month]);}}//increasethedatebyonemonthDate&Date::operator++(){if(++month>=13){month=1;year++;}return*this;}boolDate::operator==(constDate&date){returnyear==date.year&&month==date.month&&day==date.day;}boolDate::operator!=(constDate&date){returnyear!=date.year||month!=date.month||day!=date.day;}boolDate::operator<=(constDate&date){boolflag=false;if(year<date.year)flag=true;else{if(year==date.year&&month<date.month)flag=true;if(year==date.year&&month==date.month&&day<=date.day)flag=true;}returnflag;}istream&operator>>(istream&in,Date&date){cout<<"Enteradate\n";in>>date.year>>date.month>>date.day;returnin;}ostream&operator<<(ostream&out,Date&date){out<<date.day<<"/"<<date.month<<"/"<<date.year<<endl;returnout;}intmain(){Datetoday(2019,13,21);cout<<++today;Dateday(2019,12,11);if(today==day)cout<<"theyarethesameday\n";if(today!=day)cout<<"theyaredifferentday\n";if(day<=today)cout<<"onedayislessthantheother\n";return0;}4.#include<iostream>usingnamespacestd;classCVector{public:CVector();CVector(int,int);CVector(constCVector&);CVector&operator++();friendCVectoroperator+(CVector&,CVector&);friendostream&operator<<(ostream&,CVector&);~CVector();private:intx,y;};CVector::CVector(){x=y=0;}CVector::CVector(int_x,int_y):x(_x),y(_y){}CVector::CVector(constCVector&vector){x=vector.x;y=vector.y;}CVector::~CVector(){}CVector&CVector::operator++(){x++;y++;return*this;}CVectoroperator+(CVector&vec1,CVector&vec2){returnCVector(vec1.x+vec2.x,vec1.y+vec2.y);}ostream&operator<<(ostream&out,CVector&vec){out<<vec.x<<","<<vec.y;returnout;}intmain(){CVectorvector1;++vector1;cout<<vector1<<endl;CVectorvector2=vector1;cout<<vector2<<endl;CVectorvector3;vector3=vector1+vector2;cout<<vector3<<endl;return0;}5.#include<iostream>usingnamespacestd;classInteger{public:Integer(int=0);Integer(constInteger&);Integer&operator++();friendbooloperator<(Integer&,Integer&);voidprint()const;private:intvalue;};Integer::Integer(inti):value(i){}Integer::Integer(constInteger&i){value=i.value;}Integer&Integer::operator++(){++value;//orvalue++;return*this;}booloperator<(Integer&m,Integer&n){returnm.value<n.value;}voidInteger::print()const{cout<<value<<endl;}intmain(){Integern1,n2(10);Integern3=n1;n3.print();++n3;n3.print();if(n2<n3)n3.print();elsen2.print();return0;}6.#include<iostream>usingnamespacestd;classCounter{public:Counter(int=0);Counteroperator++(int);friendostream&operator<<(ostream&,Counter&);private:intvalue;};Counter::Counter(intv):value(v){}CounterCounter::operator++(int){Countertemp=*this;value++;returntemp;}ostream&operator<<(ostream&out,Counter&counter){out<<counter.value<<endl;returnout;}intmain(){Countercounter;cout<<counter++;cout<<counter;return0;}7.#include<iostream>#include<cstddef>#include<ctime>#include<cstdlib>usingnamespacestd;classArray{public:Array(size_t);intoperator[](size_t);//getanelementofanarrayint&operator()(s
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 建筑设施保养协议
- 设备回购合同样本
- 2024年度版权保护合同:国际音乐版权保护与授权协议
- 煤炭买卖合同规定
- 购销合同鱼的知识产权
- 学生犯错保证书范文小学生悔过故事
- 一份合格的驾驶安全保证书如何炼成
- 稻谷采购请求协议
- 招标文件模板设计心得体会
- 旅游服务合同的合规风险
- 生物统计与试验设计课件
- 生物技术为精准医疗注入新动力
- 2024年高级经济师之工商管理题库(历年真题)
- 《linux操作系统应用》课程标准
- 《公务员回避制度》课件
- 全市体育中考成绩分析报告
- 四川省凉山州西昌市2023-2024学年四年级上学期期末数学试卷
- 康复护理的历史发展
- 初中物理教学经验分享
- 烟花爆竹从业人员安全培训试题
- Part1-2 Unit3 Internship教案-【中职专用】高一英语精研课堂(高教版2021·基础模块2)
评论
0/150
提交评论