



版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
實驗十一類與對象.參照實驗案例,定義Date日期類。其數據成員包括年year,月month,日day。定義構造函數、析構函數。構造函數要對初始化數據進行合法性檢查。(年份4位數,月份1-12,日期根據年份、月份判斷其合法范圍)。成員函數有調整日期,顯示日期(“****年??月??日”)。〃程序設計如下:#include<iostream.h>#include<fstream.h>classDate{intyear,month,day;staticconstintdays[2][13];boolLeapYear();public:Date(int=1900,int=1,int=1);~Date(){};voidSetDate(int,int,int);voidShowDate();};constintDate::days[2][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31));Date::Date(inty,intm,intd){SetDate(y,m,d);)voidDate::SetDate(inty,intm,intd){year=(y>=1900&&y<=9999)?y:1900;month=(m>=l&&m<=12)?m:l;day=(d>=l&&d<=days[LeapYear()][month])?d:1;}voidDate::ShowDate(){coutvvyearv〈"年"vvmonthvv"月"vvdayvv"日"v<endl;}boolDate::LeapYear(){return((year%400=0)ll(year%4==0&&year%100!=0))?true:false;)intmain(){Datedl(l899,13,32)02(20001,4),d3(2004,2,29),d4;dl.ShowDate();d2.ShowDate();d3.ShowDate();d4.ShowDate();d3.SetDate(2011,2,29);d3.ShowDate();return0;).在第1題基礎上,為Date類定義日期增減函數Add(int),Reduce(血),其中參數為增減的天數。#include<iostream.h>#include<fstream.h>classDate{intyear,month,day;staticconstintdays[2][13];boolLeapYear();public:Date(int=1900,int=l,int=1);?Dale(乂};voidSetDate(int,int,int);voidShowDate();voidAdd(int);voidReduce(int);boolEndofMonth();};constintDate::days[2][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31});Date::Date(inty,intm,intd){SetDate(y,m,d);)voidDate::SetDate(inty,intm,intd){year=(y>=1900&&y<=9999)?y:1900;month=(m>=l&&m<=12)?m:l;day=(d>=1&&d<=days[LeapYear()][month])?d:1;}voidDate::ShowDate(){couivvyearvv"年"vvmonthvv”月,,?day?,*Hn?endl;}boolDate::LeapYear(){return((year%400==0)ll(year%4==0&&year%100!=0))?true:false;)boolDate::EndofMonth(){returnday==daysILeapYear()][month];)voidDate::Add(intn){for(inti=0;i<n;i++)if(EndofMonth()&&month==12){year++;month=day=1;)elseif(EndofMonth()){month++;day=1;)elseday++;}voidDate::Reduce(intn){for(inti=0;i<n;i++)if(day==l){if(month==l){year—;month=12;day=31;}elseday=days[LeapYear()][-month];)elseday--;intmain(){Datedl(2009,12,23)42(2007,2,27),d3(2008,2,27),d4(2011,1,4);dl.ShowDate();d2.ShowDate();d3.ShowDate();d4.ShowDate();dl.Add(lO);d2.Add(5);d3.Add(5);d4.Reduce(10);dl.ShowDate();d2.ShowDate();d3.ShowDate();d4.ShowDate();return0;)3.建立一個分數類Fraction。其數據成員包括分子nume和分母deno。成員函數包括構造函數、析構函數。構造函數要對初始化數據進行必要的檢查(分母不能為〇)。成員函數包括約分、通分、加、減、乘、除、求倒數、比較大小、顯示和數據輸入等,顯示函數以“a/b”形式顯示分數。完成所有成員函數的定義并在主函數中進行檢驗。程序設計如下:定義ー個Fraction類classFraction)private: 〃這句語句可以省去intnume;intdeno;public:Fraction(inti=l,intn=0){ 〃復制構造函數if(i!=0){nume=i;deno=n;)elsenume=l;deno=0;voidyuefen();FractionaddFraction(Fractiont);FractioncutFraction(Fractiont);FractionchengfaFraction(Fractiont);FractionchufaFraction(Fractiont);voiddaoshu();voidshow();};c.cpp#include<iostream>#include<cmath>#include',Fraction.h,,usingnamespacestd;voidFraction::yuefen(){intr,i=abs(nume),j=abs(deno);while(j){r=i%j;i=j;j=r;)nume/=i;deno/=i;}voidFraction::addFraction(Fractiont){inti=deno;deno=deno*t.deno;nume=nume*t.deno+t.nume*i;)voidFraction::cutFraction(Fractiont){inti=deno;deno=deno*t.deno;nume=nume*t.deno-t.nume*i;voidFraction::chengfaFraction(Fractiont){deno=deno*t.deno;nume=nume*t.nume;)voidFraction::chufaFraction(Fractiont){deno=deno*t.nume;nume=nume*t.deno;)voidFraction::daoshu(){inti;i=nume;nume=deno;deno=i;)voidFraction::show(){cout?nume?,7,'?deno?endl;main.cpp#include<iostream>#include"Fraction.h,,usingnamespacestd;intmain(){intn,d,ne,de;coutvv"請輸入分母n=";cin?n;coutvv"請輸入分子d=";cin?d;Fractiont(n,d);cout?nt=H;t.show();coutvv"請輸入分母ne二”;cin?ne;coutvv”請輸入分子de=";cin?de;Fractioni(ne,de);cout?Mi=K;i.yuefenQ;i.show();coutvぐi+l=";i.addFraction(t);i.yuefen();i.show();i.cutFraction(t);i.yuefen();〃這里的I是已計算過的i.show();i.chengfaFraction(t);cout?ni*t=H;i.yuefen();i.show();cout?"t倒數是";t.yuefen();t.daoshu();t.show();return0;)實驗十二類的復制構造函數1.定義矩形類Rectangle,該類有l(wèi)eft、top、right、bottom四個數據成員函數等。在主函數中建立Rectangle對象加以驗證。〃定義頭文件classRectangle{private:doubletop;doublebottom;doubleleft;doubleright;public:Rectangle(doublei,doublej);Rectangle(Rectangle&);voidshow();,定義矩形類的構造函數、復制構造函數、讀寫數據成員函數、計算面積doublesize();};//c.cpp文件#include<iostream>#include"Rectangle.hMusingnamespacestd;Rectangle::Rectangle(doublei,doublej){top=bottom=i;left=right=j;}Rectangle::Rectangle(Rectangle&t){left=right=t.left;top=bottom=t.top;)voidRectangle::show(){coutvv”矩形的邊為:"vvendl;cout?',top=,'?top?endl?,,bottom=',?bottom?eindl?,'left=M?left?endl?,'right="?right?endl;doubleRectangle::size(){doubles=top*left;returns;)min.cpp文件#include<iostream>#includeMRectangle.hHusingnamespacestd;intmain(){coutvv”請輸入矩形的四條邊"vvendl;doublet;double1;cin?t?1;RectangleT(t,l);T.show();RectangleB(T);coutvv”矩形的面積為:"v<T.size()vvendl;return0;.為實驗H??ー實驗內容第1題的Date類定義復制構造函數。設計fun函數。在主函數中設計相應的語句調用fun函數,理解在調用該函數過程中復制構造函數被3次調用的過程。Datefun(Dated){Dated1=d;dl.add(4);returnd1;)代碼部分如下://Date.h文件〃定義一〃定義一個Date類protected:intYear;intMonth;intDay;public:Date(Date&d){Year=d.Year;Month=d.Month;Day=d.Day;)Date(intyear=1000,intmonth=l,intday=l); //Date的構造函數~Date(乂}; //Date的析構函數voidSetDate(intyeanintmonth,intday); 〃設置時間函數voidShowDate(); 〃顯示時間函數intInspectY(intm,intn); 〃判斷year是否符合要求intInspectM(intm,intn); 〃判斷month是否符合要求intInspectD(intyear,intmonth,intday); 〃判斷I!期voidAdd(intn);voidReduce(intn);voidchoice(intn);friendDatefun(Dated););//c.cpp文件#include<iostream>#includeMDate.h"usingnamespacestd;inta1u={31,28,31,30,31,30,31,31,30,31,30,31);inta2[]={31,29,31,30,31,30,31,31,30,31,30,31);int*p;Date::Date(intyear,intmonth,intday){inta=1000,b=12;Year=InspectY(year,a);Month=InspectM(month,b);Day=InspectD(year,month,day);}voidDate::SelDate(intyear,intmonth,intday){inta=1000,b=12;Year=InspectY(year,a);Month=InspectM(month,b);Day=InspectD(year,month,day);}intDate::InspectM(intm,intn){elsereturnm;intDate:InspectY(intmjntn){if(m<1000)return1000;elsereturnm;)intDate::InspectD(intyear,intmonth,intday){if((year%400==0)ll((year%4==0)&&(year%100!ニ0))){if(month==2){if(day>29llday<=0)return1;elsereturnday;))elseif(month=2){if(day>=29llday<=0)return1;elsereturnday;if(month==4llmonth==6llmonth==9llmonth=11){if(day>30llday<=0)return1;elsereturnday;}else{if(day>3lllday<=0)return1;elsereturnday;}}voidDate::ShowDate()Icout?Year?"^"?Month<<"月"?Day?"0";}voidDate::choice(intn){if((n%400==0)ll((n%4==0)&&(n%100!=0)))P=a2;elsep=al;IvoidDate::Add(intn){choice(Year);n=n+Day-p[Month-1];for(inti=Month;n>0;i++){if(i%12==0){Year++;choice(Year);)n=n-p[i%12];)if(i%12==0)Month=12;elseMonth=i%12;Day=n+p[(i-1)%12];voidDate::Reduce(intn){choice(Year);n=n-Day;Month—;while(n>=0){if(Month==0){Month=12;Year—;choice(Year);)n=n-p[Month-l];Month—;}Month++;Day=-n;}Datefun(Dated){Datedl=d;dl.Add(4);returnd1;}//main.cpp文件#include<iostream>#includenDate.h"usingnamespacestd;intmain(){intyear,month,day,n;coutvv”輸入年份Year=M;cin?year;coutvv”輸入月份Monthゴ;cin?month;coutvv”輸入日期Dayゴ;cin?day;Datedate(year,month,day),datel;date.ShowDate();cout?endl;coutcv”調用fun函數”vvendl;datel=fun(date);dateLShowDate();cout?endl;return0;).定義組合類DateTime,類中的成員有實驗十一中的Date類和Time類的成員。定義DateTime的構造函數和復制構造函數。并在主函數中實例化DateTime類的對象。//datetime.h文件classDate{ 〃定義ー個Date類protected:intYear;intMonth;intDay;public:Date(intyear,intmonth,intday); //Date的構造函數?Date(乂}; //Date的析構函數Date(Date&date);voidShowDale。;〃顯示時間函數intInspectY(intm,intn); 〃判斷year是否符合要求intInspectM(intm,intn); 〃判斷month是否符合要求intInspectD(intyear,intmonth,intday); 〃判斷日期friendclassDateTime;);classTime{intHour;intMinte;intSecond;public:Time(inth,intm,ints);Time(Time&T);intchoicehour(inth);intchoicetime(intm);voidShowTime();friendclassDateTime;);classDateTime{DateD;TimeT;public:DateTime(Dated,Timet):D(d),T(t){}DateTime(DateTime&DT):D(DT.D),T(DT.T){};voidShowDateTime(););//c.cpp文件#include<iostream>#include,'Datelime.h,'usingnamespacestd;Date::Date(intyear,intmonth,intday){inta=1000,b=12;Year=InspectY(year,a);Month=InspectM(month,b);Day=InspectD(year,month,day);intDate::InspectM(intm,intn){if(m>n)return1;elsereturnm;)intDate::InspectY(intm,intn){if(m<1000)return1000;elsereturnm;}intDate::InspectD(intyear,intmonth,intday){if((year%400==0)ll((year%4==0)&&(year%100!=0))){if(month==2){if(day>29llday<=0)return1;elsereturnday;)elseif(month==2){if(day>=29llday<=0)return1;elsereturnday;)if(month==4llmonth==6llmonth==9llmonth==lif(day>30llday<=0)return1;elsereturnday;)else{if(day>31llday<=0)return1;elsereturnday;})Date::Date(Date&date){Year=date.Year;Month=date.Month;1)(Day=date.Day;)voidDate::ShowDate(){coulvvYearvv“年“vvMonlhvv"月”vvDayvv”日)Time::Time(inth,intm,ints){Hour=choicehour(h);Minte=choicetime(m);Second=choicetime(s);}Time::Time(Time&T){Hour=T.Hour;Minte=T.Minte;Second=T.Second;)intTime::choicehour(inth){if(h<=0llh>24){couivv”輸入有誤,強制至為「‘vvendl;return1;)elsereturnh;)intTime::choicetime(intm){if(m<0llm>60){coutvv”輸入有誤,強制至為ド<vendl;return1;}elsereturnm;)voidTime::ShowTime(){cout?Hour?n:"?Minte?H:"?Second?endl;)voidDateTime::ShowDateTime(){D.ShowDate();T.ShowTime();//main.cpp文件#include<iostream>#include,'DateTime.h"usingnamespacestd;intmain(){inty,mn,d,h,m,s;coutvv”請輸入年ア;cin?y;coutvv”請輸入月:“;cin?mn;coutvv”請輸入日:”;cin?d;Dateda(y,mn,d);cout?”輸入時間Hourゴ;cin?h;coutvv”輸入時間Minte=";cin?m;coulvv”輸入時間second=";cin?s;Timet(h,m,s);DateTimeDT(da,t);DT.ShowDateTime();return0;).改寫案例2,要求如下:定義和案例2相同的點類Points三角形類Triangle定義如下:classTriangle{public:Triangle(Point,Point,Point);Triangle(Triangle&);doubleGetArea();private:Pointpl,p2,p3;doublearea;完成Triangle類的成員函數的定義,并在主函數中定義3個Point對象,〃定義一個point類和Triangle類classPoint{protected:intX,Y;public:Point(intx=0,inty=0){X=x;Y=y;)Point(Point&P){X=P.X;Y=P.Y;)friendclassTriangle;voidShowpoint(););classTriangle{1個Triangle對象,計算三角形的面枳。public:Triangle(Point,Point,Point);Triangle(Triangle&);doubleGetArea();doublele(Pointa,Pointb);private:Pointpl,p2,p3;doublearea;};//c.cpp文件#include<iostream>#include"point.h"#include<cmath>usingnamespacestd;voidPoint::Showpoint()(cout?M(n?X?,'.H?Y?,,),,?endl;}Triangle::Triangle(Pointa,Pointb,Pointc):p1(a),p2(b),p3(c){double11,12,13;doubleav;ll=le(pl,p2);12=le(p2,p3);13=le(pl,p3);av=(l1+12+13)/2.0;area=sqrt(av*(av-l1)*(av-12)*(av-13));)Triangle::Triangle(Triangle&t):p1(t.p1),p2(t.p2),p3(t.p3){double11,12,13;doubleav;H=le(pl,p2);12=le(p2,p3);13=le(pl,p3);av=(l1+12+13)/2.0;area=sqrt(av*(av-l1)*(av-12)*(av-13));}doubleTriangle::le(Pointa,Pointb){doubledeltx=abs(a.X-b.X);doubledelty=abs(a.Y-b.Y);doublelength=sqrt(deltx*deltx+delty*delty);returnlength;)doubleTriangle::GetArea(){returnarea;)#include<iostream>#include,'point.hnusingnamespacestd;//main.cpp文件intmain(){inta,b,c,d,e,f;coutvv”請輸入六個整數"vvendl;cin?a?b?c?d?e?f;PointpeI(a,b),pe2(c,d),pe3(e,f),pe4(pe3);TriangleT(pel,pe2,pe3),Tl(peI,pe2,pe4);coutvv”三角形T的面積為:"?T.GetArea();cout?endl;coutv〈”三角形T1的面積為:"vvTl.GetArea。;cout?endl;return0;}?實驗十三類的深復制.為實驗案例中的A類定義賦值運算符的重載函數,完成對象的賦值運算。程序設計如下:〃這里的賦值是發(fā)生在調用fun函數時#include<iostream>usingnamespacestd;classA{int*p;public:A(intn){inti二n;p=newint(i);)A(A&ra){p=newint(*ra.p);}?A(){deletep;}intGetValue(){return*p;}A&operator=(A&ra){if(ra.p)p=ra.p;elsep二NULL;return*this;));intfun(Aoa){returnoa.GetValue();//new函數用于動態(tài)申請空間,并初始化〃復制構造函數完成對象的深復制〃析構函數用于釋放內存空間〃賦值運算符“ゴ’的重載voidmain(){inti;coutくく”請輸入一?個整數1=";cin>>i;Aa(i);cout?fun(a)<<endl;).設計ー個學生類(Student)。數據成員包括:身份證號(Id),姓名(Name),性別(Gender),生日(Birthday)和家庭住址(pHA)。考慮到表示每個學生家庭住址的字符長度不一,所以pHA為指向學生家庭住址的字符型指針,家庭住址的內存由new運算動態(tài)申請。要求編寫:構造函數、完成深復制的復制構造函數、釋放動態(tài)內存的析構函數、以及學生數據輸入和顯示函數。在主函數中建立Student類對象并調用成員函數。程序設計如下:〃這部分是在ー個cpp文件里完成,當然也可以分成一個頭文件,和兩個cpp文件#include<iostream>usingnamespacestd;classstudent〃定義私有成員char*pld;char*pName;char*pGender;char*pBirthday;char*pPHA;〃定義私有成員public:〃定義公有成員public:student();〃定義無參構造函數相當于默認的構造函數student(char*pname,char*pid,char*pgender,char*pbirthday,char*ppHA);〃定義含參構造函數〃定義復制構造函數〃定義析構函數〃定義復制構造函數〃定義析構函數〃重載”ゴ運算符-student();student&operator=(student&s);voidshowstudent();};student::student()(〃初始化全賦值為空pName=NULL;〃初始化全賦值為空pId=NULL;pGender=NULL;pBirthday=NULL;pPHA二NULL;)student::student(char*pname,char*pid,char*pgender,char*pbirthday,char*ppHA)if(pName=newcharlstrlen(pname)+1J)strcpy(pName,pname);if(pld=newchar[strlen(pid)+l])strcpy(pld,pid);if(pGender=newchar[strlen(pgender)+1])strcpy(pGender,pgender);if(pBirthday=newchar[strlen(pbirthday)+1])strcpy(pBirthday,pbirthday);if(pPHA=newchar[strlen(ppHA)+1])strcpy(pPHA,ppHA);)student::-student(){if(pName)pName[O]='\O';delete[]pName;if(pld)pId[O]=\O,;deletef]pld;〃利用new函數動態(tài)申請空間〃利用delete函數釋放內存空間if(pGender)pGender[O]=AO';delete[]pGender;if(pBirthday)pBirthday[〇]='\〇';delete[]pBirthday;if(pPHA)pPHA⑼=ヘ〇’;delete[]pPHA;)student::student(student&s)(if(s.pName){if(pName=newchar[strlen(s.pName)+l])strcpy(pName,s.pName);)elsepName=NULL;if(s.pld){if(pld=newchar[strlen(s.pld)+l])strcpy(pld,s.pld);)elsepId=NULL;if(s.pGender){if(pGender=newchar[strlen(s.pGender)+1])strcpy(pGender,s.pGender);}elsepGender=NULL;if(s.pBirthday){if(pBirthday=newchar[strlen(s.pBirthday)+1])strcpy(pBirthday,s.pBirthday);}elsepBirthday=NULL;if(s.pPHA){if(pPHA=newchar[strlen(s.pPHA)+1J)strcpy(pPHA,s.pPHA);)elsepPHA=NULL;)student&student::operator=(student&s){deletef]pName;if(s.pName){if(pName=newchar[strlen(s.pName)+1])strcpy(pName,s.pName);}elsepName=NULL;deletedpld;if(s.pld){if(pld=newchar[strlen(s.pld)+l])strcpy(pld,s.pld);)elsepId=NULL;delete[]pGender;if(s.pGender){if(pGender=newchar[strlen(s.pGender)+l])strcpy(pGender,s.pGender);}elsepGender=NULL;deletedpBirthday;if(s.pBirthday){if(pBirthday=newchar[strlen(s.pBirthday)+1])strcpy(pBirthday,s.pBirthday);}elsepBirthday=NULL;deletedpPHA;if(s.pPHA){if(pPHA=newchar[strlen(s.pPHA)+1])strcpy(pPHA,s.pPHA);)elsepPHA=NULL;return*this;Ivoidstudent::showstudent(){cout?pName?\t'?pId?,\t,?pGender?V?pBirthday?V,?pPHA?endl;)intmain() 〃主函數(studentsi(“張三”,”09080ド,“男”,”90.11.0ド,“南京市”);sl.showstudent();students2(”李四”,”090802”,”女”,”90.12.0ド,”常州市”),s3;s2.showstudent();cout?“"?endl;students4=s1;s4.showstudent();s3=s2;s3.showstudent();cout?endl;return0;)實驗十四友元I.將實驗十二實驗內容第1題Rectangle類中計算面積的函數定義為友元函數,程序設計如下:#include<iostream>usingnamespacestd;classRectangle{ 〃定義Rectangle類private:doubletop;doublebottom;doubleleft;doubleright;public:并在主函數中調用該友元函數計算Rectangle對象的面枳。Rectangle(doublei,doublej);Rectangle(Rectangle&);voidshow();frienddoublesize(Rectangle&); 〃定義完成面積計算的友元函數};Rectangle::Rectangle(doublei,doublej){top=bottom=i;left=right=j;}Rectangle::Rectangle(Rectangle&t){left=right=t.left;top=bottom=tlop;)voidRectangle::show(){cout<v”矩形的邊為:“vvendl;cout?ntop=n?top?endl?"bottom=n?bottom?endl?,'left=',?left?endl?,'right=n?right?endl:doublesize(Rectangle&r){doubles=r.top*r.left;returns;)intmain(){coutvv”請輸入矩形的兩組對邊值:“vvendl;doublet;double1;cin?t?l;RectangleT(t,l);T.show();coutvv”矩形的面積為:“vvsize(T)vvendl; 〃調用友元函數return0;)2.參考案例2,定義Time類的友元類DiffTime。其中DiffTime類有一個成員函數Time_DiffTime(Time&,start,Time&end)?計算兩個Time對象的時間差。程序設計如下:#include<iostream>
usingnamespacestd;classTime{private:intHounMinute,Second;public:Time();Time(intNewH,intNewM,intNewS);voidSetTime(int,int,int);voidShowTime();?Time(乂};friendclassDiffTime;};Time::Time(){SetTime(0,0,0);}Time::Time(intNewH,intNewM,intNewS){SetTime(NewH,NewM,NewS);〃時間類的定義〃時間類的定義〃私有數據成員〃外部接口,公有成員函數〃默認構造函數〃構造函數〃設置時間的函數〃顯示時間的函數〃析構函數〃定義Time類的友元類DiffTime類Hour=NewH<0IINewH>23?0:NewH;Minute=NewM<0IINewM>59?0:NewM;Second=NewS<0IINewS>59?0:NewS;}voidTime::ShowTime(){cout?Hour?n:n?Minute?n:n?Second?endl;}classDiffTime{ //Time友元類DifiTime的定義public:TimeTime_DiffTime(Time&start,Time&end); 〃完成時間差的計算};TimeDiffTime::Time_Diffnme(Time&start,Time&end){intth,tm,ts;intcarry=0;Timett;(ts=end.Second-start.Second)>0?carry=0:ts+=60,carry=l;(tm=end.Minute-start.Minute-carry)>O?carry=O:tm+=60,carry=l;(th=end.Hour-start.Hour-60-carry)>0?carry=0:th+=24;tt.SetTime(th,tm,ts);returntt;voidmain(){Timetl(8,10,10)42(3,20,4);tl.ShowTime();t2.ShowTime();Timet; 〃該變量用于表示t!和t2的時間差DiffTimet3;t=t3.Time_DiffTime(tl,t2);t.ShowTime();?實驗十五函數模板與類模板1.編寫ー個求絕對值的函數模板,并在主函數中用int、double等類型的數據測試。程序代碼如下:#include<iostream>#include<cmath>usingnamespacestd;template<typenameT>Tmas(Tn){returnfabs(n);}intmain(){inta;doubleb;coutvv”輸入ー個整數a二”;cin?a;coutvv”輸入ー個數b=M;cin?b;cout?Hlal=u?mas<int>(a)?endl;cout?"lbl=n?mas<double>(b)?endl;return0;〃是fabs的頭文件//fabs是求浮點型的整數的函數3.設計ー個函數模板sort(),完成對數組Ta[n]的排序。程序代碼如下:#include<iostream>#include<iomanip>usingnamespacestd;template<typenameT>voidsort(Ta[],intn){Ttemp;intij;for(i=0;i<n-l;i++)for(j=0;j<n-i-1;j++)if(a|j]>aU+l]){temp=a[j];a[jj=a[j+l];a[j+l]=temp;})intmain(){intn;〃定義一個函數模板〃采用冒泡排序coutvv”輸入數組長度n=";cin?n;int*p=newint[n];for(inti=0;i<n;i++){coutvv”請輸入第"vvi+kv”個數a[,,?i?,']=M;cin?p[i];}sort<int>(p,n);for(i=0;i<n;i++){cout?setw(5)?p[i]?setw(5);if((i+1)%4==0)cout?endl; 〃保證每行輸出4個元素)return0;)*3.模仿案例2,編寫ー個通用的數組類模板Array,該類模板包含有構造函數完成數組元素的初始化。排序函數完成元素的排序。輸出函數顯示排序結果。在主函數中將Array實例化成int、double、char等對象。程序代碼如下:#include<iostream>//#include<cassert>#include<iomanip>#include<string>usingnamespacestd;template<typenameT,intn>classArray{ 〃定義ー個函數模板private:intsize;T*element;public:Array(T*A);?Array。; 〃要注意重復釋放地址的有關問題Array(Array&Ary); 〃得注意深復制方面的問題voidsort。;voidshow。;};template<typenameT,intn>Array<T,n>::Array(T*A=NULL){if(n>l)size=n;elsesize=l;element=newT[sizeJ;for(inti=O;i<size;i++)element[i]=A[i];Itemplate<typenameT,intn>Array<T,n>::-Array(){deletedelement;}template<typenameT,intn>Array<T,n>::Array(Array&Ary){size=Ary.size;element=newT[size];for(inti=O;i<size;i++)element[i]=Ary.element[i];}template<typenameT,intn>voidArray<T,n>::sort(){Ttemp;inti,j;for(i=0;i<n-l;i++)for(j=0;j<n-i-l;j++)if(element[j]>element[j+1]){temp=element[j];element[j]=element[j4-1];element[j+lJ=temp;)}template<typenameT,intn>voidArray<T,n>::show()(for(inti=O;i<n;i++){cout?setw(5)?element[i]?setw(5);if((i+l)%5==0)cout?endl;)}intmain(){coutvv”輸入數組長度c=8H?endl;intc=8;intp[8];for(inti=0;i<c;i++){couivv”請輸入第”vci+kv”個整數a[H?i?"]=n;cin?p[i];)coutvv”排好序的數組如下”<<endl;Array<int,8>intAry(p);intAry.sort();intAry.show();cout?endl;doubled[8J;for(i=0;i<c;i++){coutvv”請輸入第”vvi+l<v”個數d[,,?i?"]=n;cin?d[i];)coutvv”排好序的數組如下”vvendl;Array<double,8>douAry(d);douAry.sort();douAry.show();cout?endl;charch網;for(i=0;i<c;i++){coutvv”請輸入第"vvi+kv”個字符ch[M?i?n]=M;cin?ch[i];)coutvv”排好序的數組如下"vvendl;Array<char,8>charAry(ch);charAry.sort();charAry.show();cout?endl;return0;實驗十六繼承與派生1.首先,定義圖形基類Shape,在類中有保護數據成員:長度length和寬度width,構造函數完成數據成員的初始化。其次由Shape類公有派生出矩形類Rectangle和三角形類Triangle,每個派生類都有一個計算面積函數Area。,分別計算矩形和三角形的面積。最后在主函數中加以測試?!ǔ绦蛟O計如下:#include<iostream>#include<cmath>constdoublepi=3.14159;〃定義常變量usingnamespacestd;classShape〃定義ー個抽象類Sh叩e{public:virtualdoubleArea()const=0;Shape(){length=O;width=0;}protected:doublelength,width;);classRectangle:publicShape〃通過抽象類派生出?個矩形累public:Rectangle(double1=0,doublew=O):length(l),width(w){}〃構造函數doubleArea()const; 〃計算矩形的面積private:doublelength,widthJ 〃私有數據成員,長,寬);doubleRectangle::Area()const 〃計算矩形的面積(returnlength*width;)classTriangle:publicShape〃定義ー個三角形{public:Triangle(doublea=0,doubleb=0,doublec=0):sl(a),s2(b),s3(c){)〃構造函數doubleArea()const;private:doublesl,s2,s3; 〃私有數據成員,三邊長};doubleTriangle::Area()const 〃計算三角形的面積if((sl+s2)<=s3II(sl+s3)<=s2II(s2+s3)<=sl)return0;doubles=(sl+s2+s3)/2;returnsqrt(s*(s-sI)*(s-s2)*(s-s3));)voidprintArea(constShape&s)〃圖形面積顯示函數{coutvv”面積為:“vvs.Area。vvendl;)intmain()(Rectangler(5,10);Trianglet(5,6,7);coutcv"矩形";〃顯示矩形的面積printArea(r);coutvv"三角形〃顯示三角形的面積printArea(t);〃如果不能構成三角形return0;.將實驗ー|——中實驗案例的Time類派生出ZoneTime類,ZoneTime類增加一個表示時區(qū)的數據成員zone?編寫ZoneTime類的構造,復制構造,顯示日期、時間、時區(qū)等函數。程序設計如下:#include<iostream>#include<cstring>usingnamespacestd;classZoneTime:publicTime{intZone;intYear,Month,Day,Hour,Minute,Second;public:ZoneTime();ZoneTime(ZoneTime&);voidSetTime(intNewY,intNewMon,intNewD,intNewH,intNewMin,intNewS,intNewZ);voidShowTime();ZoneTime::ZoneTime(){Year=Hour=Minute=Second=0;Month=Day=1;ZoneTime::ZoneTime(ZoneTime&s){Zone=s.Zone;Year=s.Year;Month=s.Month;Day=s.Day;Hour=s.Hour;Minute=s.Minute;Second=s.Second;}voidZoneTime::SetTime(intNewY,intNewMonJntNewDJntNewH,intNcZone=NewZ<0IINewZ>24?0:NewZ;Month=NewMon<1IINewMon>12?0:NewMon;Day=NewD<0IINewD>31?0:NewD;Hour=NewH<0IINewH>23?0:NewH;Minute=NewMin<0IINewMin>59?0:NewMin;Second=NewS<0IINewS>59?0:NewS;iwMinJntNewSjntNewZ){voidZoneTime::ShowTime(){SetTime(intNewYjntNewMon,intNewDjntNewHJntNewMin,intNewS,intNewZ);cout?Year?,,-,,?Month?,,-,,?Day?,\t,?Hour?,,:,,?Minute?,,:,,?Second?,\t,?,,0tK^J:,,?Zone?,\n,;)voidmain(){ZoneTimemyTime;cout?,'Firsttimesetandoutput:M?endl;myTime.ShowTimeO;cout?HSecondtimesetandoutput:u?endl;myTime.SetTime(2010,12,25,10,15,20,8);myTime.ShowTimeO;cout?nThirdtimesetandoutput:"vvendl;ZoneTimemyTimel(myTime);myTime1.ShowTime();.定義一個人員基類Person,其數據成員有姓名、性別、身份證號等基本信息,函數成員包括構造函數、析構函數,用于初始化數據成員和釋放動態(tài)申請的內存,輸出基本信息的函數Perinfo()。從Person類公有派生出Student類,增加數據成員No保存學號、Profe保存專、ル。構造函數初始化基類和自身的數據。輸出基本信息函數Stuinfo輸出Student類和Person類的數據。程序代碼如下:〃定義一個類作為頭文件,person.h#defineMas19 〃宏替換#defineN9classperson{ 〃定義ー個person類protected:char*name; 〃注意深復制問題,這chargender;charID[Mas];public:person(char*p,charg,chard[]);person(person&p);-person。{
if(name!=NULL)deletedname;)voidperinfo();〃用person〃用person類派生一個student類classstudent:publicperson{private:charNo[N];char*profe;public:student(personpl,charno[],char*pro);student(student&st);?student。{if(profe!=NULL)deletedprofe;)voidstuinfo。;);//c.cpp文件#include<iostream>#include<string>#include,,Person.h,,usingnamespacestd;person::person(char*p,charg,chard[]){if(p!=NULL)if(name=newchar[strlen(p)+l])strcpy(name,p);elsename=NULL;gender=g;strcpy(ID,d);)person::person(person&p){if(!=NULL)if(name=newchar[strlen()+l])strcpy(name,);elsename=NULL;〃深復制〃strlen()求字符數組長度gender=p.gender;strcpy(ID,p.ID);voidperson::perinfo(){coutvぐ姓名:“vvnamevvendkv”性別:“vvgendervvendkv”身份證號:“vvIDvvendl;)student::student(personpl,charno[],char*pro):person(p1){strcpy(No,no);if(pro!=NULL)if(profe=newchar[strlen(pro)+1])strcpy(profe,pro);elseprofe=NULL;)student::student(student&st):person(st){strcpy(No,st.No);if(fe!=NULL)if(profe=newchar[strlen(fe)+1])strcpy(profe,fe);elseprofe=NULL;)voidstudent::stuinfo(){coutvv"學號:"vvNovvendl;perinfo();coutvv”專業(yè):n?profe?endl;}//main.cpp文件#include<iostream>#include<string>#include,,Person.h,,usingnamespacestd;intmain(){charno[N];coutvv”請輸入學號:";cin?no;char*p,na[19J;COUIVV”請輸入姓名:";cin?na;p=na;charg;coutvv”請輸入性別cin?g;chard[Mas];coutvc”請輸入身份證號:";cin?d;char*pro,zy[9];coutcv”請輸入專業(yè):”cin?zy;pro=zy;personpl(p,g,d);pl.perinfo();studentst(pl,no,pro);st.stuinfo();return0;?實驗十七多繼承與虛基類.實驗十二中實驗內容第3題類DateTime由Date類和Time類組合而成?,F在要求重新定義DateTime類,該類由Date類和Time類公有派生而來。從而理解ー個類由其它類組合而成(hasa關系)和繼承其他類(isa關系)的區(qū)別。程序代碼如下:〃定義一個頭文件DateTime.hclassDate{ 〃定義ー個Date類protected:intYear;intMonth;intDay;public:Date(intyear,intmonth,intday); //Date的構造函數?Date。{}; //Date的析構函數Date(Date&date);voidShowDate。;〃顯示時間函數intInspectY(intm,intn); 〃判斷year是否符合要求intlnspectM(intm,intn); 〃判斷month是否符合要求intInspectD(intyear,intmonth,intday); 〃判斷日期};classTime{intHour;intMinte;intSecond;public:Time(inth,intm,ints);Time(Time&T);intchoicehour(inth);intchoicetime(intm);voidShowTime();};classDateTime:publicDate,publicTime{public:DateTime(Dated,Timet):Date(d),Time(t){}DateTime(DateTime&DT):Date(DT),Time(DT){}voidShowDateTime(););//c.cpp文件如F:#include<iostream>#include,'DateTime.hHusingnamespacestd;Date::Date(intyear,intmonth,intday){inta=1000,b=12;Year=InspectY(year,a);Month=InspectM(month,b);Day=InspectD(year,month,day);}intDate::InspectM(intm,intn){if(m>n)return1;elsereturnm;intDate::InspectY(intm,intn){if(m<1000)return1000;elsereturnm;)intDate::InspectD(intyear,intmonth,intday){if((year%400==0)ll((year%4==0)&&(year%100!=0))){if(month==2){if(day>29llday<=0)return1;elsereturnday;))elseif(month==2){if(day>=29llday<=0)return1;elsereturndayif(month==4llmonth==6llmonth==9llmonth==l1){if(day>30llday<=0)return1;elsereturnday;)else{if(day>31llday<=0)return1;elsereturnday;)}Date::Date(Date&date){Year=date.Year;Month=date.Month;Day=date.Day;}voidDate::ShowDate()coutvvYearvv“年“vvMonthvv"月"vvDayvv”日”;Time::Time(inth,intmjnts){Hour=choicehour(h);Minte=choicetime(m);Second=choicetime(s);)Time::Time(Time&T){Hour=T.Hour;Minte=T.Minte;Second=T.Second;}intTime::choicehour(inth){if(h<=0llh>24){coutvv”輸入有誤,強制至為ドvvendl;return1;elsereturnh;intTime::choicetime(intm){if(m<0llm>60){coutvぐ輸入有誤,強制至為ドvvendl;return1;)elsereturnm;)voidTime::ShowTime(){cout<<Hour?',:',?Minte?M:,,?Second?endl;}voidDateTime::ShowDateTime(){ShowDate();ShowTime();}//main.cpp文件#include<iostream>#include,fDateTime.h',usingnamespacestd;intmain(){inty,mn,d,h,m,s;cout?”請輸入年:";cin?y;cout<<”請輸入月:“;cin?mn;coul<<”請輸入日:”;cin?d;Dateda(y,mn,d);cout?”輸入時間Hour=";cin?h;cout?”輸入時間Minte=M;cin?m;coutvv”輸入時間secondゴ;cin?s;DateTimeDT(da,t);DT.ShowDateTime();return0;).使用實驗十六實驗內容第3題的Person類,將其分別公有派生出專家類Technician和市長類Mayor。其中Technician類增加成員有技術專長,Mayor類增加工作城市。再由Technician類和Mayor類共同公有派生出專家市長類Tech_Mayor。為所有類定義構造、析構函數。在主函數中創(chuàng)建Tech_Mayor類對象,通過該對象訪問Person類中的成員。程序代碼如下:〃定義一個頭文件Person.h#defineMas19 〃宏替換classperson{ 〃疋義ー個person類protected:char*name; 〃注意深復制問題,這chargender;charID[Mas];public:person(char*p,charg,chard[]);person(person&p);?person(乂//delete動態(tài)生成的空間,防止空間泄露if(name!=NULL)deletef]name;)voidperinfo();};classTechnician:publicperson{protected:char*jishu;public:Technician(personp,char*js);Technician(Technician&Te);〃跟上面的name一樣注意深復制上的,空間泄露問題?〃跟上面的name一樣注意深復制上的,空間泄露問題if(jishu!=NULL)delete[]jishu;voidshowTechnician。;};classMayor:publicperson{protected:char*city;public:Mayor(personp,char*ct);Mayor(Mayor&ma);?Mayor。{if(city!=NULL)delete[Jcity;)voidshowMayor。;};classTech_Mayor:publicMayor,publicTechnician(public:Tech_Mayor(Mayorma,Techniciante):Mayor(ma),Technician(te){)Tech_Mayor(Tech_Mayor&T_M);-Tech_Mayor(){}voidshowTech_Mayor();};//c.cpp文件#include<iostream>#include<string>#include"Person.hnusingnamespacestd;person::person(char*p,charg,chard[]){if(p!=NULL)if(name=newchar[strlen(p)+l])strcpy(name,p);elsename=NULL;gender=g;strcpy(ID,d);)person::person(person&p){if(!=NULL)if(name=newchar[strlen()+l])strcpy(name,);〃深復制〃strlen()求字符數組長度〃重新動態(tài)生成一個name空間,防止空間的二次釋放elsename=NULL;gender=p.gender;strcpy(ID,p.ID);Ivoidperson::perinfb(){coutvv”姓名:“vvnamevvendkv”性另リ:“vvgendervvendlvv”身份證號:“vvIDvvendl;)Technician::Technician(personp,char*js):person(p){if(js!=NULL)if(jishu=newchar[strlen(js)+l])strcpy
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 職工車輛協(xié)議書
- 綠化管養(yǎng)協(xié)議書
- 調研合作協(xié)議書
- 簽定日期協(xié)議書
- 美容股份協(xié)議書
- 無保險車禍賠償協(xié)議書
- 股東獎勵協(xié)議書
- 留守人員協(xié)議書
- 屋面SBS防水協(xié)議書
- 夏令營活動合同協(xié)議書
- 2025棗莊事業(yè)單位筆試真題
- 2025年電子循環(huán)水泵行業(yè)深度研究報告
- 2025年平面設計師專業(yè)能力測試卷:平面設計實踐與案例分析試題
- 2025-2030年中國藏藥行業(yè)市場深度調研及前景趨勢與投資研究報告
- 統(tǒng)計局招聘試題及答案
- 消防車駕駛員基本素質、車輛行車安全
- 行政輔助考試試題及答案
- 人工智能賦能中學英語教學的創(chuàng)新路徑探究
- x監(jiān)理管理辦法
- 2025湘美版(2024)小學美術一年級下冊教學設計(附目錄)
- 人教版(2024)小學數學一年級下冊《歡樂購物街》教學設計及反思
評論
0/150
提交評論