合肥工業(yè)大學程序設(shè)計基礎(chǔ)實驗報告_第1頁
合肥工業(yè)大學程序設(shè)計基礎(chǔ)實驗報告_第2頁
合肥工業(yè)大學程序設(shè)計基礎(chǔ)實驗報告_第3頁
合肥工業(yè)大學程序設(shè)計基礎(chǔ)實驗報告_第4頁
合肥工業(yè)大學程序設(shè)計基礎(chǔ)實驗報告_第5頁
已閱讀5頁,還剩61頁未讀, 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

合肥工業(yè)大學程序設(shè)計基礎(chǔ)實驗報告姓名:班級:計算機科學與技術(shù)學號:合肥工業(yè)大學計算機與信息學院1實驗七類與對象1(實驗?zāi)康囊笳莆疹惖亩x和實現(xiàn)。掌握對象創(chuàng)建及使用的基本方法。2(實驗設(shè)備硬件環(huán)境:微型計算機軟件環(huán)境:操作系統(tǒng):Windows語言環(huán)境:VisualC++3(預(yù)習要求學習教材有關(guān)類的定義與實現(xiàn)、對象創(chuàng)建與應(yīng)用等有關(guān)內(nèi)容,對實驗基本要求應(yīng)在上機實驗前仔細閱讀,程序應(yīng)事先編制完成,上機時錄入調(diào)試,同時還應(yīng)設(shè)計相應(yīng)的測試用例集,檢查程序的正確性、可靠性、完備性和容錯能力。4(實驗內(nèi)容(1)下面程序定義了一個以hours,minutes和seconds作為數(shù)據(jù)成員的Time類。設(shè)計了成員函數(shù)將兩個Time對象相加(即時間相加),并進行相應(yīng)的檢查,查看增加的分鐘數(shù)及秒數(shù)是否大于59。如果秒數(shù)大于59,則分鐘數(shù)向前遞增1。類似地,如果分鐘數(shù)大于59,則小時數(shù)向前增1。#include<iostream>usingnamespacestd;classTime(private:inthours,minutes,seconds;public:voidget_time()(2cin>>hours>>minutes>>seconds;}voiddisplay_time()(cout<<hours<<':'<<minutes<<':'<<seconds<<endl;}voidadd_time(Time&t1,Time&t2)(hours=t1.hours+t2.hours;minutes=t1.minutes+t2.minutes;seconds=t1.seconds+t2.seconds;if(seconds>=60)seconds-=60;minutes++;}if(minutes>=60)(minutes-=60;hours++;}}};voidmain()(Timeone,two,three;cout<<"\nEnterthefirsttime(hoursminutesseconds):";one.get_time();cout<<"\nEnterthesecondtime(hoursminutesseconds):"two.get_time();three.add_time(one,two);cout<<"theresultis:"<<endl;three.display_time();}[基本要求],上機錄入、調(diào)試上面程序。,運行程序,輸入下面兩組數(shù)據(jù):2344514756267100156200分析運行結(jié)果是否正確。3[分析與思考],定義構(gòu)造函數(shù)對Time類的對象進行初始化(即不用成員函數(shù)get_time)。,該程序要求用戶輸入的分鐘數(shù)和秒數(shù)必須小于60,如何修改程序使得用戶在輸入分鐘數(shù)和秒數(shù)大于等于60時,也能得到正確的結(jié)果。結(jié)果不正確,不是預(yù)想的5,1,8說明程序不能輸入大于60的份和秒。更改后的程序為#include<iostream>std;usingnamespaceclassTime(private:inthours,minutes,seconds;public:Time(inth=0,intm=0,ints=0):hours(h),minutes(m),seconds(s){}voiddisplay_time()(cout<<hours<<':'<<minutes<<':'<<seconds<<endl;}voidadd_time(Time&t1,Time&t2)(4hours=t1.hours+t2.hours;minutes=t1.minutes+t2.minutes;seconds=t1.seconds+t2.seconds;while(seconds>=60)(seconds-=60;minutes++;while(minutes>=60)(minutes-=60;hours++;}}};voidmain()(Timeone(2,34,45),two(1,47,56),three;three.add_time(one,two);three.display_time();}(2)閱讀下面的一段程序代碼,代碼可能有錯誤,請仔細分析并體會。classDate(public:voidDate()(};intDate(intyear,intmonth,intday);void~Date()(};int&GetYear(){returnyear;}int&GetMonth()(returnmonth;}int&GetDay()(returnday;}private:intyear=2000;intmonth=12;intday=31;staticboolIsLeapyear;//是否閏年};boolDate::IsLeapyear二true;intDate::Date(intyear,intmonth,intday)5((*this).year二year;(*this).month二month;(*this).day=day;}voidmain()(intyear,month,day;cin>>year>>month>>day;Datemydate(year,month,day);int&myyear二mydate.GetYear();int&mymonth=mydate.GetMonth();int&myday=mydate.GetDay();cout<<myyear<<endl<<mymonth<<endl<<myday<<endl;myyear=8888;cout<<mydate.GetYear();}[基本要求]仔細閱讀上面程序,如果有錯誤,請更正。上機錄入、調(diào)試上面程序。[分析和思考]main函數(shù)中int&myyear二mydate.GetYear();、int&mymonth二mydate.GetMonth();和int&myday=mydate.GetDay();語句表達的是什么思想,這樣做的目的是什么,這種方法是否“好”呢,為什么,如果“不好”應(yīng)該怎樣修改,修改后的程序:#include<iostream>usingnamespacestd;classDate(public:Date(intyear=2000,intmonth=12,intday=31);~Date(){};int&GetYear()(returnyear;}int&GetMonth()(returnmonth;}int&GetDay()(returnday;}private:intyear;intmonth;intday;staticboolIsLeapyear;};6boolDate::IsLeapyear二true;year,intmonth,intday)Date::Date(int((*this).year二year;(*this).month二month;(*this).day二day;}voidmain()(intyear,month,day;cin>>year>>month>>day;Datemydate(year,month,day);int&myyear二mydate.GetYear();int&mymonth=mydate.GetMonth();int&myday=mydate.GetDay();cout<<myyear<<endl<<mymonth<<endl<<myday<<endl;myyear=8888;cout<<mydate.GetYear();}輸入19900607得到成匚;ndewj'jy7te-i132\r.vid.emt17?0Q607L7?0h罪購清鞍任意鍵舲?■.分析:語句的意義是為了讓本不可以調(diào)用的私有成員,可以利用公有成員函數(shù)在主函數(shù)中得到一個引用的變量,也就是可以用引用的變量來修改類中私有成員。但是這種做法并不可取,因為類的封裝性,這樣就破壞的類的封裝性,沒有保護好私有成員。刪掉即可。7實驗八繼承與派生類1(實驗?zāi)康囊笳莆諉卫^承程序設(shè)計的基本方法。掌握多繼承程序設(shè)計的基本方法。2(實驗設(shè)備硬件環(huán)境:微型計算機軟件環(huán)境:操作系統(tǒng):Windows語言環(huán)境:VisualC++3(預(yù)習要求學習教材有關(guān)繼承與派生類的內(nèi)容,對單繼承語義、繼承控制和訪問控制,多繼承的多義性及其解決方法有充分的理解和把握。對實驗基本要求應(yīng)在上機實驗前仔細閱讀,程序應(yīng)事先編制完成,上機時錄入調(diào)試,同時還應(yīng)設(shè)計相應(yīng)的測試用例集,檢查程序的正確性、可靠性、完備性和容錯能力。4(實驗內(nèi)容(1)下面程序定義一個vehicle類,并派生出car和truck兩個派生類。#include<iostream.h>classvehicle(protected:intwheels;doubleweight;public:voidinitialize(intwhls,doublewght);intget_wheels()(returnwheels;}doubleget_weight()(returnweight;}doublewheel_loading()(returnweight/wheels;}};classcar:publicvehicle(private:8intpassenger_load;public:voidinitialize(intwhls,doublewght,intpeople=4);intpassengers()(returnpassenger_load;}};classtruck:publicvehicle(private:intpassenger_load;doublepayload;public:voidinit_truck(intnumber=2,doublemax_load=24000.0);doubleefficiency();intpassengers()(returnpassenger_load;});voidvehicle::initialize(intwhls,doublewght)(wheels=whls;weight=wght;}voidcar::initialize(intwhls,doublewght,intpeople)(wheels=whls;weight=wght;passenger_load=people;}voidtruck::init_truck(intnumber,doublemax_load)(passenger_load=number;payload=max_load;}doubletruck::efficiency()(returnpayload/(payload+weight);}voidmain()(vehiclebicycle;9bicycle.initialize(2,25);cout<<"thebicyclehas"<<bicycle.get_wheels()<<"wheels.\n”;cout<<"thebicycleweighs"<<bicycle.get_weight()<<"pounds.\n”;cout<<"thebicycle'swheelloadingis"<<bicycle.wheel_loading()<<"poundspertire.\n\n”;caraudi;audi.initialize(4,3500.0,5);cout<<"theaudihas"<<audi.get_wheels()<<"wheels.\n”;cout<<"theaudiweighs"<<audi.get_weight()<<"pounds.\n”;cout<<"theaudi'swheelloadingis"<<audi.wheel_loading()<<"poundspertire.\n\n”;truckjief;jief.initialize(18,12500.0);jief.init_truck(2,33675.0);cout<<"thejiefhas"<<jief.get_wheels()<<"wheels.\n”;cout<<"thejiefweighs"<<jief.get_weight()<<"pounds.\n”;cout<<"thejief'sefficiencyis〃<<100.0*jief.efficiency()<<〃percent.\n〃;}[基本要求],上機錄入、調(diào)試上面程序。,運行程序,觀察運行結(jié)果是否正確且滿足題意要求。,將classcar:publicvehicle和classtruck:publicvehicle分別改為:classcar:privatevehicle和classtruck:privatevehicle程序運行結(jié)果有無變化,為什么,[分析與思考],定義并實現(xiàn)vehicle類、car類和truck類的構(gòu)造函數(shù),完成vehicle類、car類和truck類的數(shù)據(jù)成員初始化工作。,將vehicle中數(shù)據(jù)成員wheels和weight改為private性質(zhì),如何修改程序以達到相同的輸出結(jié)果。答:修改前和修改后的結(jié)果都是gQC:\Wmdom技kcmdf牌thebitIihm2 _rhebicweighs2^poiEnds,thehieycle■suhee1loaclinyis12.5paurttCsperttre.rheaadihas4wheeIstheAAjLdl youn職.thea/LiliJeuhcaliQ-adis87Spoundspe■略tthejicfhas13wheels.thftjiefighs1#日瞬pciinii^FthejiefJseFFicLencyis72.9-291percent.清按荏怠踵匪霽…10分析:如果將兩個繼承都改成私有繼承,不僅使wheel和weight成員變量沒辦法繼承,而且公有成員函數(shù)像get_wheel()都不能被類外調(diào)用,解決的辦法有可以設(shè)一個在派生類和基類公有成員函數(shù)調(diào)用本類私有成員,類外調(diào)用公有成員函數(shù)即可。思考題#include<iostream.h>classvehicle(protected:intwheels;doubleweight;public:vehicle(intwhls,doublewght)(wheels=whls;weight=wght;}intget_wheels()(returnwheels;}doubleget_weight()(returnweight;}doublewheel_loading()(returnweight/wheels;}};classcar:publicvehicle(private:intpassenger_load;public:car(intwhls,doublewght,intpeople=4):vehicle(whls,wght)(passenger_load=people;}intpassengers()(returnpassenger_load;}};classtruck:publicvehicle(private:intpassenger_load;doublepayload;public:11truck(intwhls,doublewght,intnumber=2,doublemax_load=24000.0):vehicle(whls,wght)(passenger_load=number;payload=max_load;}doubleefficiency()(returnpayload/(payload+weight);}intpassengers()(returnpassenger_load;}};voidmain()(vehiclebicycle(2,25);cout<<"thebicyclehas"<<bicycle.get_wheels()<<"wheels.\n”;cout<<"thebicycleweighs〃<<bicycle.get_weight()<<〃pounds.\n”;cout<<"thebicycle'swheelloadingis"<<bicycle.wheel_loading()<<"poundspertire.\n\n”;caraudi(4,3500.0,5);cout<<"theaudihas"<<audi.get_wheels()<<"wheels.\n”;cout<<"theaudiweighs"<<audi.get_weight()<<"pounds.\n”;cout<<"theaudi'swheelloadingis"<<audi.wheel_loading()<<"poundspertire.\n\n”;truckjief(18,12500.0,2,33675.0);cout<<"thejiefhas"<<jief.get_wheels()<<"wheels.\n”;cout<<"thejiefweighs"<<jief.get_weight()<<"pounds.\n”;cout<<"thejief'sefficiencyis〃<<100.0*jief.efficiency()<<〃percent.\n”;}2.基類保護成員改為似有成員:#include<iostream.h>classvehicle(private:intwheels;doubleweight;public:vehicle(intwhls,doublewght)12(wheels=whls;weight=wght;}intget_wheels()(returnwheels;}doubleget_weight()(returnweight;}doublewheel_loading()(returnweight/wheels;}};classcar:publicvehicle(private:intpassenger_load;public:car(intwhls,doublewght,intpeople=4):vehicle(whls,wght)(passenger_load=people;}intpassengers()(returnpassenger_load;}};classtruck:publicvehicleprivate:intpassenger_load;doublepayload;doubleweight;public:truck(intwhls,doublewght,intnumber=2,doublemax_load=24000.0):vehicle(whls,wght)(passenger_load=number;payload=max_load;weight=wght;}doubleefficiency()(returnpayload/(payload+weight);}intpassengers()(returnpassenger_load;}};voidmain()13(vehiclebicycle(2,25);cout<<"thebicyclehas"<<bicycle.get_wheels()<<"wheels.\n”;cout<<"thebicycleweighs"<<bicycle.get_weight()<<"pounds.\n”;cout<<"thebicycle'swheelloadingis"<<bicycle.wheel_loading()<<poundspertire.\n\n”;caraudi(4,3500.0,5);cout<<"theaudihas"<<audi.get_wheels()<<"wheels.\n”;cout<<"theaudiweighs"<<audi.get_weight()<<"pounds.\n”;cout<<"theaudi'swheelloadingis"<<audi.wheel_loading()<<"poundspertire.\n\n”;truckjief(18,12500.0,2,33675.0);cout<<"thejiefhas"<<jief.get_wheels()<<"wheels.\n”;cout<<"thejiefweighs"<<jief.get_weight()<<"pounds.\n”;cout<<"thejief'sefficiencyis〃<<100.0*jief.efficiency()<<〃percent.\n”;}(2)下面程序?qū)?yīng)圖1所示的類層次繼承結(jié)構(gòu):#include<iostream.h>personperson#include<iomanip.h>#include<string.h>teachergraduateclassperson(protected:charname[20];in-service_graduateintbirth_year;public:person(char*na,intyear)(strcpy(name,na);birth_year=year;}intcal_age(intthis_year)(returnthis_year-birth_year;}};14classgraduate:publicperson(protected:intgrade;charspecialty[20];public:graduate(char*na,inty,intg,char*spec):person(na,y)(grade=g;strcpy(specialty,spec);}voiddisplay(intthis_year)(cout<<"graduateagegradespecialty\n”;cout<<setw(20)<<name<<setw(5)<<cal_age(this_year);cout<<setw(7)<<grade<<setw(17)<<specialty<<endl;}};classteacher:publicperson(protected:chartitle[15];charspecialty[20];public:teacher(char*na,inty,char*ti,char*spec):person(na,y)(strcpy(title,ti);strcpy(specialty,spec);}voiddisplay(intthis_year)(cout<<"teacheragetitlespecialty\n”;cout<<setw(20)<<name<<setw(5)<<cal_age(this_year);cout<<setw(14)<<title<<setw(17)<<specialty<<endl;}};classin_service_graduate:publicteacher,publicgraduate(public:in_service_graduate(char*na,inty,char*ti,char*spec1,intg,char*spec2):teacher(na,y,ti,spec1),graduate(na,y,g,spec2)(}voiddisplay(intthis_year)(cout<<"in_service_graduateagetitlework_specialtygradestudy_specialty\n”;15}};voidmain()(graduategr(〃zhang_ling〃,1978,2001,〃computer〃);teacherte("wang_qiang",1976,〃tutor〃,〃electronics〃);in_service_graduatesg(〃liu_hua〃,1975,〃lectuer〃,〃automation〃,2002,〃computer〃);gr.display(2002);cout<<endl;te.display(2002);cout<<endl;sg.display(2002);}[基本要求],閱讀程序,完成in_service_graduate類中的display()函數(shù)的程序。,上機錄入、調(diào)試上面程序。,運行程序,觀察運行結(jié)果是否正確且滿足題意要求。[分析與思考],在上面程序中類person中的數(shù)據(jù)成員name和birth_year在in_service_graduate類中有兩個副本,請使用虛基類使它們在in_service_graduate類中只有一個副本。注意同時修改程序的其他相關(guān)部分。將函數(shù)繼承改成虛基類:#include<iostream>#include<iomanip>#include<string>usingnamespacestd;classperson16(protected:charname[20];intbirth_year;public:person(char*na,intyear)(strcpy(name,na);birth_year=year;}intcal_age(intthis_year)(returnthis_year-birth_year;}};protected:intgrade;charspecialty[20];public:graduate(char*na,inty,intg,char*spec):person(na,y)(grade=g;strcpy(specialty,spec);}voiddisplay(intthis_year)(cout<<"graduateagegradespecialty\n”;cout<<setw(20)<<name<<setw(5)<<cal_age(this_year);cout<<setw(7)<<grade<<setw(17)<<specialty<<endl;}};classteacher:virtualpublicperson(protected:chartitle[15];charspecialty[20];public:teacher(char*na,inty,char*ti,char*spec):person(na,y)(strcpy(title,ti);strcpy(specialty,spec);voiddisplay(intthis_year)(cout<<"teacheragetitlespecialty\n”;cout<<setw(20)<<name<<setw(5)<<cal_age(this_year);17cout<<setw(14)<<title<<setw(17)<<specialty<<endl;}};classin_service_graduate:publicteacher,publicgraduate(public:in_service_graduate(char*na,inty,char*ti,char*spec1,intg,char*spec2):teacher(na,y,ti,spec1),graduate(na,y,g,spec2),person(na,y)(}display(intthis_year)(voidcout<<"in_service_graduateagetitlework_specialtygradestudy_specialty\n”;cout<<setw(15)<<name<<setw(9)<<cal_age(this_year)<<setw(10)<<title;cout<<setw(15)<<teacher::specialty<<setw(8)<<grade<<setw(13)<<graduate::specialty<<endl;}};voidmain()graduategr(〃zhang_ling〃,1978,2001,〃computer〃);teacherte("wang_qiang",1976,〃tutor〃,〃electronics〃);in_service_graduatesg(〃liu_hua〃,1975,〃lectuer〃,〃automation〃,2002,〃computer〃);gr.display(2002);cout<<endl;te.display(2002);cout<<endl;sg.display(2002);}18實驗九多態(tài)性與虛函數(shù)1(實驗?zāi)康恼莆仗摵瘮?shù)定義及實現(xiàn)。掌握具有多態(tài)性的面向?qū)ο蟪绦蛟O(shè)計的基本方法。掌握純虛函數(shù)與抽象類的定義、實現(xiàn)及應(yīng)用。2(實驗設(shè)備硬件環(huán)境:微型計算機軟件環(huán)境:操作系統(tǒng):Windows語言環(huán)境:VisualC++3(預(yù)習要求學習教材有關(guān)多態(tài)性與虛函數(shù)的內(nèi)容,對靜態(tài)聯(lián)編、動態(tài)(滯后)連編、對象指針等充分的理解。對實驗基本要求應(yīng)在上機實驗前仔細閱讀,程序應(yīng)事先編制完成,上機時錄入調(diào)試,同時還應(yīng)設(shè)計相應(yīng)的測試用例集,檢查程序的正確性、可靠性、完備性和容錯能力。4(實驗內(nèi)容有一個整數(shù)鏈表,現(xiàn)從此鏈表派生出一個整數(shù)集合類,在集合類中增加一個元素個數(shù)的數(shù)據(jù)項。集合類的插入操作與鏈表相似,只是不插入重復(fù)元素,并且插入后,元素個數(shù)的數(shù)據(jù)成員需增加。集合類的刪除操作是在鏈表刪除操作的基礎(chǔ)上對元素個數(shù)做減1操作。而查找和輸出操作是相同的,因此在集合類中不需要重復(fù)定義。#include<iostream.h>#include<conio.h>//enumbool{false,true};structelement(//定義鏈表中的結(jié)點結(jié)構(gòu)intval;element*next;};classlist(//定義鏈表類element*elems;public:list()(elems=0;}19~list();virtualboolinsert(int);〃此虛函數(shù)在派生類中可重新定義virtualbooldeletes(int);//此虛函數(shù)在派生類中可重新定義boolcontain(int);voidprint();};classset:publiclist(〃將集合類set定義為鏈表類list的派生類intcard;public:set()(card=0;}boolinsert(int);//重定義此函數(shù)booldeletes(int);//重定義此函數(shù)};list::~list()//list類得析構(gòu)函數(shù)定義,循環(huán)釋放各元素所占的存儲{element*tmp二elems;for(element*elem=elems;elem!=0;)(tmp=elem;elem=elem->next;deletetmp;}}boollist::insert(intval)//定義list類中插入元素的成員函數(shù){element*elem=newelement;//為新元素分配存儲if(elem!=0)(elem->val=val;//將新元素插入到鏈表頭elem->next=elems;elems=elem;returntrue;}elsereturnfalse;}boollist::deletes(intval)〃定義list類中刪除元素的成員函數(shù){if(elems==0)returnfalse;//若表為空,返回falseelement*tmp二elems;if(elems->val==val)(//若待刪除的元素為表頭元素elems=elems->next;deletetmp;20returntrue;}elsefor(element*elem=elems;elem->next!=0;elem=elem->next)if(elem->next->val==val)(//循環(huán)查找待刪除元素tmp=elem->next;elem->next=tmp->next;deletetmp;returntrue;}returnfalse;}boollist::contain(intval)(//判元素val在鏈表中是否存在if(elems==0)returnfalse;if(elems->val==val)returntrue;elsefor(element*elem=elems;elem->next!=0;elem=elem->next)if(elem->next->val==val)returntrue;returnfalse;}voidlist::print()//輸出鏈表中各元素(if(elems==0)return;for(element*elem=elems;elem!=0;elem=elem->next)cout<<elem->val<<"";cout<<endl;}boolset::insert(intval)〃在set類中的insert的重定義版本{if((1))(〃先判斷此元素是否存在,然后再調(diào)用基類的此函數(shù)版本++card;returntrue;}returnfalse;}boolset::deletes(intval)//在set類中的deletes的重定義版本{if(list::deletes(val))//調(diào)用基類中的此函數(shù)版本21((2);returntrue;}returnfalse;}intmain()(list*ptr,list1;setset1;ptr=&list1;ptr->insert(30);ptr->insert(40);ptr->insert(543);ptr->insert(40);ptr->print();ptr=&set1;ptr->insert(23);ptr->insert(672);ptr->insert(456);ptr->insert(23);ptr->print();getch();return1;}[基本要求],閱讀程序,根據(jù)題意要求在處填上合適的內(nèi)容完成程序。,上機錄入、調(diào)試上面程序。,運行程序,設(shè)計測試數(shù)據(jù),觀察運行結(jié)果是否正確且滿足題意要求。[分析與思考],在list類中設(shè)計并實現(xiàn)一個從鏈表頭取一個節(jié)點(取出后該結(jié)點刪除,下一個結(jié)點作為頭結(jié)點)并返回節(jié)點值(整數(shù)值)的成員函數(shù)。,在集合類中增加求集合并、交、差的成員函數(shù)。填完后源碼如下:#include<iostream>#include<conio.h>usingnamespacestd;structelement(intval;element*next;};classlist(element*elems;22public:list(){elems=0;}~list();virtualboolinsert(int);virtualbooldeletes(int);boolcontain(int);voidprint();};classset:publiclist(intcard;public:set()(card=0;}boolinsert(int);booldeletes(int);};list::~list()(element*tmp二elems;for(element*elem=elems;elem!=0;)(tmp=elem;elem=elem->next;deletetmp;}boollist::insert(intval)(element*elem二newelement;if(elem!=0)(elem->val=val;elem->next=elems;elems=elem;returntrue;}elsereturnfalse;}boollist::deletes(intval)(if(elems==0)returnfalse;element*tmp=elems;23if(elems->val==val)(elems=elems->next;deletetmp;returntrue;}elsefor(element*elem=elems;elem->next!=0;elem=elem->next)if(elem->next->val==val)tmp=elem->next;elem->next=tmp->next;tmp;deletereturntrue;}returnfalse;}boollist::contain(intval)(if(elems==0)returnfalse;if(elems->val==val)returntrue;elsefor(element*elem=elems;elem->next!=0;elem=elem->next)if(elem->next->val==val)returntrue;returnfalse;}voidlist::print()(if(elems==0)return;for(element*elem=elems;elem!=0;elem=elem->next)cout<<elem->val<<"";cout<<endl;boolset::insert(intval)(if((contain(val))?0:list::insert(val))(++card;returntrue;}24returnfalse;}boolset::deletes(intval)(if(list::deletes(val))(--card;returntrue;}returnfalse;}main()int(list*ptr,list1;setset1;ptr=&list1;ptr->insert(30);ptr->insert(40);ptr->insert(543);ptr->insert(40);ptr->print();ptr=&set1;ptr->insert(23);ptr->insert(672);ptr->insert(456);ptr->insert(23);ptr->print();getch();return1;}輸出結(jié)果為:FEBCWind-am3cinnd.exe符合要求25實驗十運算符重載1(實驗?zāi)康恼莆者\算符重載的定義及實現(xiàn)。掌握具有運算符重載的應(yīng)用。2(實驗設(shè)備硬件環(huán)境:微型計算機軟件環(huán)境:操作系統(tǒng):Windows語言環(huán)境:VisualC++3(預(yù)習要求學習教材有關(guān)運算符重載的內(nèi)容,對基本運算符重載及特殊運算符重載有充分的理解。對實驗基本要求應(yīng)在上機實驗前仔細閱讀,程序應(yīng)事先編制完成,上機時錄入調(diào)試,同時還應(yīng)設(shè)計相應(yīng)的測試用例集,檢查程序的正確性、可靠性、完備性和容錯能力。4(實驗內(nèi)容(1)將一個16位二進制數(shù)表示成0和1的字符序列,即用一個字符數(shù)組來存放這個二進制數(shù)。在這個類中設(shè)置兩個構(gòu)造函數(shù),一個是傳遞整數(shù)參數(shù)的,另一個是傳遞字符串參數(shù)的。因為用戶在創(chuàng)建對象時傳遞的二進制數(shù),可能是以整數(shù)形式給出,也可能是以數(shù)字串形式給出,系統(tǒng)應(yīng)該都能接受。另外有一個類型轉(zhuǎn)換函數(shù)int(),用來將類類型向整型轉(zhuǎn)換。程序中的兩個重載運算符“+”,"-”,用來完成兩個二進制數(shù)之間的加減運算。#include"iostream.h"#include"string.h"#include"conio.h"classbinary(//定義二進制類charbits[16];//二進制字模數(shù)組public:binary(char*);//字符串參數(shù)構(gòu)造函數(shù)binary(int);//整型參數(shù)構(gòu)造函數(shù)friendbinaryoperator+(binary,binary);//重載"+”friendbinaryoperator-(binary,binary);//重載"-”operatorint();〃類類型轉(zhuǎn)換函數(shù)voidprint();};26binary::binary(char*num)(intisrc=strlen(num)-1;〃字符串長度-1為最低位intidest=15;while(isrc>=0&&idest>=0)bits[idest--]=(num[isrc--]=='0'?'0':'1');//逐位賦值while(idest>=0)bits[idest--]='0';//空高位值0}binary::binary(intnum)(for(inti=15;i>=0;i--)(bits[i]=(num%2==0?'0':T;)//求余數(shù)num>>=1;//移位,相當于整除2}}binaryoperator+(binaryn1,binaryn2)(unsignedcarry=0;unsignedvalue;binaryres=”0”;for(inti=15;i>=0;i--)(value=(n1.bits[i]=='0'?0:1)+(n2.bits[i]=='0'?0:1)+carry;res.bits[i]=(value%2==0?'0':T');carry=value>>1;}returnres;}binaryoperator-(binaryn1,binaryn2)(unsignedborrow=0;intvalue;binaryres="0";for(inti=15;i>=0;i--)(value=(n1.bits[i]=='0'?0:1)-(n2.bits[i]=='0'?0:1)+borrow;res.bits[i]=(value==T||value==1?T':'0‘);borrow=(value==-1||borrow!=0&&(value==0||value==1)?1:0);}returnres;}binary::operatorint()(unsignedvalue=0;for(inti=0;i<=15;i++)value=(value*2)+(bits[i]=='0'?0:1);returnvalue;}voidbinary::print()(charstr[17];strncpy(str,bits,16);str[16]='\0';cout<<str<<"\n";}main()(binaryn1=〃1011”;binaryn2=int(n1)+15;binaryn3=n1-binary(7);n1.print();n2.print();n3.print();cout<<int(n2)+5<<endl;cout<<n2-binary(5)<<endl;cout<<n3+binary(5)<<endl;cout<<int(n3)-5<<endl;getch();return1;}[基本要求],閱讀下列程序,根據(jù)題意要求在處填上合適的內(nèi)容完成程序。,上機錄入、調(diào)試上面程序。,運行程序,紀錄并分析運行結(jié)果是否正確。在程序中填上的內(nèi)容為:num%2==0?'0':T‘n2.bits[i]=='0'?0:1(3)value*228運行的結(jié)果為:fleesooeeeeGeiBiiseooeBaeeeciiBia白臼白色白臼臼臼怕臼自白Q1r房按任意譴縫舞…-[分析與思考]1)將+、-運算符定義為binary類的成員函數(shù)。(重載運算符?、&、|分別將二進制數(shù)按位取反、數(shù)按位與及按位或。(2)編寫一個集合類,重載+(并集)、-(差集)、*(交集)、<<(輸出)、>>(輸入)等函數(shù)。思考題(1)#include<iostream>#include<string>#include<conio.h>usingnamespacestd;classbinary(charbits[16];public:binary(char*);binary(int);binaryoperator+(binary);binaryoperator-(binary);operatorint();voidprint();};binary::binary(char*num)(intisrc=strlen(num)-1;intidest=15;while(isrc>=0&&idest>=0)bits[idest--]=(num[isrc--]=='0'?'0':'1');29while(idest>=0)bits[idest--]='0';binary::binary(intnum)(for(inti=15;i>=0;i--)(bits[i]=(num%2==0?'0':T');num>>=1;}}binarybinary::operator+(binaryn)(unsignedcarry=0;unsignedvalue;binaryres=”0”;for(inti=15;i>=0;i--)(value=(bits[i]=='0'?0:1)+(n.bits[i]=='0'?0:1)+carry;res.bits[i]=(value%2==0?'0':T');carry=value>>1;}returnres;}binarybinary::operator-(binaryn)(unsignedborrow=0;intvalue;binaryres=”0”;for(inti=15;i>=0;i--)(value=(bits[i]=='0'?0:1)-(n.bits[i]=='0'?0:1)+borrow;res.bits[i]=(value==T||value==1?T':'0‘);borrow=(value==-1||borrow!=0&&(value==0||value==1)?1:0);}returnres;}binary::operatorint()(unsignedvalue=0;for(inti=0;i<=15;i++)value=(value*2)+(bits[i]=='0'?0:1);returnvalue;30}voidbinary::print()(charstr[17];strncpy(str,bits,16);str[16]='\0';cout<<str<<"\n";intmain()(binaryn1=〃1011”;(n1)+15;binaryn2=intbinaryn3=n1-binary(7);n1.print();n2.print();n3.print();cout<<int(n2)+5<<endl;cout<<n2-bi

溫馨提示

  • 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)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論