c++實(shí)驗(yàn)程序參考答案_第1頁
c++實(shí)驗(yàn)程序參考答案_第2頁
c++實(shí)驗(yàn)程序參考答案_第3頁
c++實(shí)驗(yàn)程序參考答案_第4頁
已閱讀5頁,還剩174頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

實(shí)驗(yàn)十一類與對象.參照實(shí)驗(yàn)案例,定義Date日期類。其數(shù)據(jù)成員包括年year,月month,日day。定義構(gòu)造函數(shù)、析構(gòu)函數(shù)。構(gòu)造函數(shù)要對初始化數(shù)據(jù)進(jìn)行合法性檢查。(年份4位數(shù),月份1-12,日期根據(jù)年份、月份判斷其合法范圍)。成員函數(shù)有調(diào)整日期,顯示日期(“****年??月??日”)。〃程序設(shè)計(jì)如下:#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題基礎(chǔ)上,為Date類定義日期增減函數(shù)Add(int),Reduce(血),其中參數(shù)為增減的天數(shù)。#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.建立一個分?jǐn)?shù)類Fraction。其數(shù)據(jù)成員包括分子nume和分母deno。成員函數(shù)包括構(gòu)造函數(shù)、析構(gòu)函數(shù)。構(gòu)造函數(shù)要對初始化數(shù)據(jù)進(jìn)行必要的檢查(分母不能為〇)。成員函數(shù)包括約分、通分、加、減、乘、除、求倒數(shù)、比較大小、顯示和數(shù)據(jù)輸入等,顯示函數(shù)以“a/b”形式顯示分?jǐn)?shù)。完成所有成員函數(shù)的定義并在主函數(shù)中進(jìn)行檢驗(yàn)。程序設(shè)計(jì)如下:定義ー個Fraction類classFraction)private: 〃這句語句可以省去intnume;intdeno;public:Fraction(inti=l,intn=0){ 〃復(fù)制構(gòu)造函數(shù)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是已計(jì)算過的i.show();i.chengfaFraction(t);cout?ni*t=H;i.yuefen();i.show();cout?"t倒數(shù)是";t.yuefen();t.daoshu();t.show();return0;)實(shí)驗(yàn)十二類的復(fù)制構(gòu)造函數(shù)1.定義矩形類Rectangle,該類有l(wèi)eft、top、right、bottom四個數(shù)據(jù)成員函數(shù)等。在主函數(shù)中建立Rectangle對象加以驗(yàn)證。〃定義頭文件classRectangle{private:doubletop;doublebottom;doubleleft;doubleright;public:Rectangle(doublei,doublej);Rectangle(Rectangle&);voidshow();,定義矩形類的構(gòu)造函數(shù)、復(fù)制構(gòu)造函數(shù)、讀寫數(shù)據(jù)成員函數(shù)、計(jì)算面積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;.為實(shí)驗(yàn)H??ー實(shí)驗(yàn)內(nèi)容第1題的Date類定義復(fù)制構(gòu)造函數(shù)。設(shè)計(jì)fun函數(shù)。在主函數(shù)中設(shè)計(jì)相應(yīng)的語句調(diào)用fun函數(shù),理解在調(diào)用該函數(shù)過程中復(fù)制構(gòu)造函數(shù)被3次調(diào)用的過程。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的構(gòu)造函數(shù)~Date(乂}; //Date的析構(gòu)函數(shù)voidSetDate(intyeanintmonth,intday); 〃設(shè)置時間函數(shù)voidShowDate(); 〃顯示時間函數(shù)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”調(diào)用fun函數(shù)”vvendl;datel=fun(date);dateLShowDate();cout?endl;return0;).定義組合類DateTime,類中的成員有實(shí)驗(yàn)十一中的Date類和Time類的成員。定義DateTime的構(gòu)造函數(shù)和復(fù)制構(gòu)造函數(shù)。并在主函數(shù)中實(shí)例化DateTime類的對象。//datetime.h文件classDate{ 〃定義ー個Date類protected:intYear;intMonth;intDay;public:Date(intyear,intmonth,intday); //Date的構(gòu)造函數(shù)?Date(乂}; //Date的析構(gòu)函數(shù)Date(Date&date);voidShowDale。;〃顯示時間函數(shù)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”輸入有誤,強(qiáng)制至為「‘vvendl;return1;)elsereturnh;)intTime::choicetime(intm){if(m<0llm>60){coutvv”輸入有誤,強(qiáng)制至為ド<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相同的點(diǎn)類Points三角形類Triangle定義如下:classTriangle{public:Triangle(Point,Point,Point);Triangle(Triangle&);doubleGetArea();private:Pointpl,p2,p3;doublearea;完成Triangle類的成員函數(shù)的定義,并在主函數(shù)中定義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對象,計(jì)算三角形的面枳。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”請輸入六個整數(shù)"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;}?實(shí)驗(yàn)十三類的深復(fù)制.為實(shí)驗(yàn)案例中的A類定義賦值運(yùn)算符的重載函數(shù),完成對象的賦值運(yùn)算。程序設(shè)計(jì)如下:〃這里的賦值是發(fā)生在調(diào)用fun函數(shù)時#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函數(shù)用于動態(tài)申請空間,并初始化〃復(fù)制構(gòu)造函數(shù)完成對象的深復(fù)制〃析構(gòu)函數(shù)用于釋放內(nèi)存空間〃賦值運(yùn)算符“ゴ’的重載voidmain(){inti;coutくく”請輸入一?個整數(shù)1=";cin>>i;Aa(i);cout?fun(a)<<endl;).設(shè)計(jì)ー個學(xué)生類(Student)。數(shù)據(jù)成員包括:身份證號(Id),姓名(Name),性別(Gender),生日(Birthday)和家庭住址(pHA)。考慮到表示每個學(xué)生家庭住址的字符長度不一,所以pHA為指向?qū)W生家庭住址的字符型指針,家庭住址的內(nèi)存由new運(yùn)算動態(tài)申請。要求編寫:構(gòu)造函數(shù)、完成深復(fù)制的復(fù)制構(gòu)造函數(shù)、釋放動態(tài)內(nèi)存的析構(gòu)函數(shù)、以及學(xué)生數(shù)據(jù)輸入和顯示函數(shù)。在主函數(shù)中建立Student類對象并調(diào)用成員函數(shù)。程序設(shè)計(jì)如下:〃這部分是在ー個cpp文件里完成,當(dāng)然也可以分成一個頭文件,和兩個cpp文件#include<iostream>usingnamespacestd;classstudent〃定義私有成員char*pld;char*pName;char*pGender;char*pBirthday;char*pPHA;〃定義私有成員public:〃定義公有成員public:student();〃定義無參構(gòu)造函數(shù)相當(dāng)于默認(rèn)的構(gòu)造函數(shù)student(char*pname,char*pid,char*pgender,char*pbirthday,char*ppHA);〃定義含參構(gòu)造函數(shù)〃定義復(fù)制構(gòu)造函數(shù)〃定義析構(gòu)函數(shù)〃定義復(fù)制構(gòu)造函數(shù)〃定義析構(gòu)函數(shù)〃重載”ゴ運(yùn)算符-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函數(shù)動態(tài)申請空間〃利用delete函數(shù)釋放內(nèi)存空間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() 〃主函數(shù)(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;)實(shí)驗(yàn)十四友元I.將實(shí)驗(yàn)十二實(shí)驗(yàn)內(nèi)容第1題Rectangle類中計(jì)算面積的函數(shù)定義為友元函數(shù),程序設(shè)計(jì)如下:#include<iostream>usingnamespacestd;classRectangle{ 〃定義Rectangle類private:doubletop;doublebottom;doubleleft;doubleright;public:并在主函數(shù)中調(diào)用該友元函數(shù)計(jì)算Rectangle對象的面枳。Rectangle(doublei,doublej);Rectangle(Rectangle&);voidshow();frienddoublesize(Rectangle&); 〃定義完成面積計(jì)算的友元函數(shù)};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; 〃調(diào)用友元函數(shù)return0;)2.參考案例2,定義Time類的友元類DiffTime。其中DiffTime類有一個成員函數(shù)Time_DiffTime(Time&,start,Time&end)?計(jì)算兩個Time對象的時間差。程序設(shè)計(jì)如下:#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);〃時間類的定義〃時間類的定義〃私有數(shù)據(jù)成員〃外部接口,公有成員函數(shù)〃默認(rèn)構(gòu)造函數(shù)〃構(gòu)造函數(shù)〃設(shè)置時間的函數(shù)〃顯示時間的函數(shù)〃析構(gòu)函數(shù)〃定義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); 〃完成時間差的計(jì)算};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();?實(shí)驗(yàn)十五函數(shù)模板與類模板1.編寫ー個求絕對值的函數(shù)模板,并在主函數(shù)中用int、double等類型的數(shù)據(jù)測試。程序代碼如下:#include<iostream>#include<cmath>usingnamespacestd;template<typenameT>Tmas(Tn){returnfabs(n);}intmain(){inta;doubleb;coutvv”輸入ー個整數(shù)a二”;cin?a;coutvv”輸入ー個數(shù)b=M;cin?b;cout?Hlal=u?mas<int>(a)?endl;cout?"lbl=n?mas<double>(b)?endl;return0;〃是fabs的頭文件//fabs是求浮點(diǎn)型的整數(shù)的函數(shù)3.設(shè)計(jì)ー個函數(shù)模板sort(),完成對數(shù)組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;〃定義一個函數(shù)模板〃采用冒泡排序coutvv”輸入數(shù)組長度n=";cin?n;int*p=newint[n];for(inti=0;i<n;i++){coutvv”請輸入第"vvi+kv”個數(shù)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,編寫ー個通用的數(shù)組類模板Array,該類模板包含有構(gòu)造函數(shù)完成數(shù)組元素的初始化。排序函數(shù)完成元素的排序。輸出函數(shù)顯示排序結(jié)果。在主函數(shù)中將Array實(shí)例化成int、double、char等對象。程序代碼如下:#include<iostream>//#include<cassert>#include<iomanip>#include<string>usingnamespacestd;template<typenameT,intn>classArray{ 〃定義ー個函數(shù)模板private:intsize;T*element;public:Array(T*A);?Array。; 〃要注意重復(fù)釋放地址的有關(guān)問題Array(Array&Ary); 〃得注意深復(fù)制方面的問題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”輸入數(shù)組長度c=8H?endl;intc=8;intp[8];for(inti=0;i<c;i++){couivv”請輸入第”vci+kv”個整數(shù)a[H?i?"]=n;cin?p[i];)coutvv”排好序的數(shù)組如下”<<endl;Array<int,8>intAry(p);intAry.sort();intAry.show();cout?endl;doubled[8J;for(i=0;i<c;i++){coutvv”請輸入第”vvi+l<v”個數(shù)d[,,?i?"]=n;cin?d[i];)coutvv”排好序的數(shù)組如下”vvendl;Array<double,8>douAry(d);douAry.sort();douAry.show();cout?endl;charch網(wǎng);for(i=0;i<c;i++){coutvv”請輸入第"vvi+kv”個字符ch[M?i?n]=M;cin?ch[i];)coutvv”排好序的數(shù)組如下"vvendl;Array<char,8>charAry(ch);charAry.sort();charAry.show();cout?endl;return0;實(shí)驗(yàn)十六繼承與派生1.首先,定義圖形基類Shape,在類中有保護(hù)數(shù)據(jù)成員:長度length和寬度width,構(gòu)造函數(shù)完成數(shù)據(jù)成員的初始化。其次由Shape類公有派生出矩形類Rectangle和三角形類Triangle,每個派生類都有一個計(jì)算面積函數(shù)Area。,分別計(jì)算矩形和三角形的面積。最后在主函數(shù)中加以測試。〃程序設(shè)計(jì)如下:#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){}〃構(gòu)造函數(shù)doubleArea()const; 〃計(jì)算矩形的面積private:doublelength,widthJ 〃私有數(shù)據(jù)成員,長,寬);doubleRectangle::Area()const 〃計(jì)算矩形的面積(returnlength*width;)classTriangle:publicShape〃定義ー個三角形{public:Triangle(doublea=0,doubleb=0,doublec=0):sl(a),s2(b),s3(c){)〃構(gòu)造函數(shù)doubleArea()const;private:doublesl,s2,s3; 〃私有數(shù)據(jù)成員,三邊長};doubleTriangle::Area()const 〃計(jì)算三角形的面積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)〃圖形面積顯示函數(shù){coutvv”面積為:“vvs.Area。vvendl;)intmain()(Rectangler(5,10);Trianglet(5,6,7);coutcv"矩形";〃顯示矩形的面積printArea(r);coutvv"三角形〃顯示三角形的面積printArea(t);〃如果不能構(gòu)成三角形return0;.將實(shí)驗(yàn)ー|——中實(shí)驗(yàn)案例的Time類派生出ZoneTime類,ZoneTime類增加一個表示時區(qū)的數(shù)據(jù)成員zone?編寫ZoneTime類的構(gòu)造,復(fù)制構(gòu)造,顯示日期、時間、時區(qū)等函數(shù)。程序設(shè)計(jì)如下:#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,其數(shù)據(jù)成員有姓名、性別、身份證號等基本信息,函數(shù)成員包括構(gòu)造函數(shù)、析構(gòu)函數(shù),用于初始化數(shù)據(jù)成員和釋放動態(tài)申請的內(nèi)存,輸出基本信息的函數(shù)Perinfo()。從Person類公有派生出Student類,增加數(shù)據(jù)成員No保存學(xué)號、Profe保存專、ル。構(gòu)造函數(shù)初始化基類和自身的數(shù)據(jù)。輸出基本信息函數(shù)Stuinfo輸出Student類和Person類的數(shù)據(jù)。程序代碼如下:〃定義一個類作為頭文件,person.h#defineMas19 〃宏替換#defineN9classperson{ 〃定義ー個person類protected:char*name; 〃注意深復(fù)制問題,這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;〃深復(fù)制〃strlen()求字符數(shù)組長度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"學(xué)號:"vvNovvendl;perinfo();coutvv”專業(yè):n?profe?endl;}//main.cpp文件#include<iostream>#include<string>#include,,Person.h,,usingnamespacestd;intmain(){charno[N];coutvv”請輸入學(xué)號:";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;?實(shí)驗(yàn)十七多繼承與虛基類.實(shí)驗(yàn)十二中實(shí)驗(yàn)內(nèi)容第3題類DateTime由Date類和Time類組合而成。現(xiàn)在要求重新定義DateTime類,該類由Date類和Time類公有派生而來。從而理解ー個類由其它類組合而成(hasa關(guān)系)和繼承其他類(isa關(guān)系)的區(qū)別。程序代碼如下:〃定義一個頭文件DateTime.hclassDate{ 〃定義ー個Date類protected:intYear;intMonth;intDay;public:Date(intyear,intmonth,intday); //Date的構(gòu)造函數(shù)?Date。{}; //Date的析構(gòu)函數(shù)Date(Date&date);voidShowDate。;〃顯示時間函數(shù)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”輸入有誤,強(qiáng)制至為ドvvendl;return1;elsereturnh;intTime::choicetime(intm){if(m<0llm>60){coutvぐ輸入有誤,強(qiáng)制至為ド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;).使用實(shí)驗(yàn)十六實(shí)驗(yàn)內(nèi)容第3題的Person類,將其分別公有派生出專家類Technician和市長類Mayor。其中Technician類增加成員有技術(shù)專長,Mayor類增加工作城市。再由Technician類和Mayor類共同公有派生出專家市長類Tech_Mayor。為所有類定義構(gòu)造、析構(gòu)函數(shù)。在主函數(shù)中創(chuàng)建Tech_Mayor類對象,通過該對象訪問Person類中的成員。程序代碼如下:〃定義一個頭文件Person.h#defineMas19 〃宏替換classperson{ 〃疋義ー個person類protected:char*name; 〃注意深復(fù)制問題,這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一樣注意深復(fù)制上的,空間泄露問題?〃跟上面的name一樣注意深復(fù)制上的,空間泄露問題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,);〃深復(fù)制〃strlen()求字符數(shù)組長度〃重新動態(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)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論