《《C++大学教程第五版》课后习题答案2.pdf》由会员分享,可在线阅读,更多相关《《C++大学教程第五版》课后习题答案2.pdf(51页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、C+大学基础教程课后答案(DEITEL)版3.11GradeBook 类定义:#include /p rog ram uses C+standard string classusing std:string;class GradeBook(p ublic:/constructor initializes course name and instructor nameGradeBook(string,string );void setCourseName(string );/function to set the course namestring g etCourseName();/funct
2、ion to retrieve the course namevoid setlnstructorName(string );/function to set instructor namestring g etlnstructorNameO;/function to retrieve instructor namevoid disp layMessag e();/disp lay welcome messag e and instructor namep rivate:string courseName;/course name for this GradeBookstring instru
3、ctorName;/instructor name for this GradeBook;/end class GradeBook类成员函数:include using std:cout;using std:endl;#include GradeBook,h”/constructor initializes courseName and instructorName/with string s sup p lied as arg umentsGradeBook:GradeBook(string course,string instructor)(setCourseName(course);/i
4、nitializes courseNamesetlnstructorName(instructor);/initializes instructorName /end GradeBook constructor/function to set the course namevoid GradeBook:setCourseName(string name)(courseName=name;/store the course name /end function setCourseName/function to retrieve the course namestring GradeBook:g
5、 etCourseName()(return courseName;/end function g etCourseName/function to set the instructor namevoid GradeBook:setlnstructorName(string name)(instructorName=name;/store the instructor name /end function setlnstructorName/function to retrieve the instructor namestring GradeBook:g etI nstructorName(
6、)(return instructorName;/end function g etI nstructorName/disp lay a welcome messag e and the instructor,s namevoid GradeBook:disp layMessag e()(/disp lay a welcome messag e containing the course namecout ”Welcome to the g rade book forn g etCourseName()!endl;/disp lay the instructor,s namecout ”Thi
7、s course is p resented by:g etlnstructorName()endl;/end function disp layMessag e测试文件:include using std:cout;using std:endl;/include definition of class GradeBook from GradeBook,hinclude GradeBook,h”/function main beg ins p rog ram executionint mainO(/create a GradeBook object;p ass a course name an
8、d instructor nameGradeBook g radeBook(“CS1O1 I ntroduction to C+Prog ramming”,Professor Smith);/disp lay initial value of instructorName of GradeBook objectcout ”g radeBook instructor name i s:“g radeBook.g etlnstructorName()”nn;/modify the instructorName using set functiong radeBook.setlnstructorNa
9、me(Assistant Professor Bates);/disp lay new value of instructorNamecout ”new g radeBook instructor name i s:“g radeBook.g etlnstructorName()”nn;/disp lay welcome messag e and instructor,s nameg radeBook.disp layMessag e();return 0;/indicate successful termination /end main3.12类定义:class Account(p ubl
10、ic:Account(int);/constructor initializes balancevoid credit(int);/add an amount to the account balancevoid debit(int);/subtract an amount from the account balanceint g etBalance();/return the account balancep rivate:int balance;/data member that stores the balance;/end class Account类成员函数:#include us
11、ing std:cout;using std:endl;#include Account,h/include definition of class Account/Account constructor initializes data member balanceAccount:Account(int initialBalance)(balance=0;/assume that the balance beg ins at 0/if initialBalance is g reater than 0,set this value as the/balance of the Account;
12、otherwise,balance remains 0if(initialBalance 0)balance=initialBalance;/if initialBalance is neg ative,p rint error messag eif(initialBalance balance)/debit amount exceeds balancecout ”Debit amount exceeded account balance.n endl;if(amount=balance)/debit amount does not exceed balancebalance=balance-
13、amount;/end function debit/return the account balanceint Account:g etBalance()return balance;/g ives the value of balance to the calling function /end function g etBalance测试函数:include using std:cout;using std:cin;using std:endl;/include definition of class Account from Account,hinclude Account,h”/fu
14、nction main beg ins p rog ram executionint mainO(Account account1(50);/create Account objectAccount account2(25);/create Account object/disp lay initial balancecout ”account1 balance:cout z,account2 balance:of each object$account 1.g etBalance()$account2.g etBalance()endl;endl;int withdrawalAmount;/
15、stores withdrawal amount read from usercout ”nE nter withdrawal amount for account1:/p romp tcin withdrawalAmount;/obtain user inp utcout z,nat temp ting to subtract withdrawal Amount “from account1 balancenn”;account 1.debit(withdrawalAmount);/try to subtract from account 1/disp lay balancescout ac
16、count1 balance:$accountl.g etBalance()endl;cout ”account?balance:$account2.g etBalance()endl;cout ”nE nter withdrawal amount for account2:/p romp tcin withdrawalAmount;/obtain user inp utcout zznat temp ting to subtract withdrawal Amount “from account2 balancenn”;account2.debit(withdrawal Amount);/t
17、ry to subtract from account2/disp lay balancescout ”accountl balance:$“accountl.g etBalance()endl;cout ”account2 balance:$“account2.g etBalance()endl;return 0;/indicate successful termination /end main3.13类定义:include /p rog ram uses C+standard string classusing std:string;/I nvoice class definitionc
18、lass I nvoice(p ublic:/constructor initializes the four data membersI nvoice(string,string,int,int);/set and g et functions for the four data membersvoid setPartNumber(string );/p art numberstring g etPartNumber();void setPartDescrip tion(string );/p art descrip tionstring g etPartDescrip tionO;void
19、 setQuantity(int);/quantityint g etQuantity();void setPricePerI tem(int);/p rice p er itemint g etPricePerltemO;/calculates invoice amount by multip lying quantity x p rice p er itemint g etlnvoiceAmount();p rivate:string p artNumber;/the number of the p art being soldstring p artDescrip tion;/descr
20、ip tion of the p art being soldint quantity;/how many of the items are being soldint p ricePerltem;/p rice p er item;/end class I nvoice类成员函数:Winclude using std:cout;using std:endl;/include definition of class I nvoice from I nvoice,h#include I nvoice,h”/I nvoice constructor initializes the class,s
21、four data membersI nvoice:I nvoice(string number,string descrip tion,int count,int p rice)(setPartNumber(number);/store p artNumbersetPartDescrip tion(descrip tion);/store p artDescrip tionsetQuantity(count);/validate and store quantitysetPricePerI tem(p rice);/validate and store p ricePerltem /end
22、I nvoice constructor/set p art numbervoid Invoice:setPartNumber(string number)(partNumber=number;/no validation needed /end function setPartNumber/get part numberstring Invoice:getPartNumber()(return partNumber;/end function getPartNumber/set part descriptionvoid Invoice:setPartDescription(string de
23、scription)(partDescription=description;/no validation needed /end function setPartDescription/get part descriptionstring Invoice:getPartDescription()return partDescription;/end function getPartDescription/set quantity;if not positive,set to 0void Invoice:setQuantity(int count)(if(count 0)/if quantit
24、y is positivequantity=count;/set quantity to countif(count 0)/if price is positivepricePerltem=price;/set pricePerltem to priceif(price=0)/if price is not positive(pricePerltem=0;/set pricePerltem to 0cout /znpricePerItem cannot be negative.”p ricePerltem set to 0.n”;/end if /end function setPricePe
25、rltem/g et p rice p er itemint I nvoice:g etPricePerI tem()(return p ricePerltem;/end function g etPricePerltem/calulates invoice amount by multip lying quantity x p rice p er itemint I nvoice:g etI nvoiceAmount()(return g etQuantity()*g etPricePerltem();/end function g etlnvoiceAmount测试函数:#include
26、using std:cout;using std:cin;using std:endl;/include definition of class I nvoice from I nvoice,hinclude I nvoice,h”/function main beg ins p rog ram executionint main()(/create an I nvoice objectI nvoice invoice(“12345,H ammer”,100,5);/disp lay the invoice data members and calculate the amountcout ”
27、Part number:“invoice.g etPartNumber()endl;cout ”Part descrip tion:“invoice.g etPartDescrip tion()endl;cout ”Quantity:“invoice.g etQuantity()endl;cout ”Price p er item:$“invoice.g etPricePerltem()endl;cout ”I nvoice amount:$invoice.g etlnvoiceAmount()endl;/modify the invoice data membersinvoice.setPa
28、rtNumber(123456);invoice.setPartDescrip tion(Saw);invoice.setQuantity(-5);/neg ative quantity,so quantity set to 0invoice.setPricePerltem(10);cout ”nlnvoice data members modified.nnz,;/disp lay the modified invoice data members and calculate new amountcout ”Part number:invoice.g etPartNumber()endl;c
29、out ”Part descrip tion:“invoice.g etPartDescrip tion()endl;cout ”Quantity:invoice.g etQuantity()endl;cout ”Price p er item:$“invoice.g etPricePerltem()endl;cout ”I nvoice amount:$“invoice.g etlnvoiceAmount()endl;return 0;/indicate successful termination /end main3.14类定义:include /p rog ram uses C+sta
30、ndard string classusing std:string;/E mp loyee class definitionclass E mp loyee(p ublic:E mp loyee(string,string,int);/constructor sets data membersvoid setF irstName(string );/set first namestring g etF irstNameO;/return first namevoid setLastName(string );/set last namestring g etLastName();/retur
31、n last namevoid setMonthlySalary(int);/set weekly salaryint g etMonthlySalary();/return weekly salaryp rivate:string firstName;/E mp loyee1 s first namestring lastName;/E mp loyee,s last nameint monthlySalary;/E mp loyee,s salary p er month;/end class E mp loyee类成员函数:#include using std:cout;include“
32、E mp loyee,h/E mp loyee class definition/E mp loyee constructor initializes the three data membersE mp loyee:E mp loyee(string first,string last,int salary)(setF irstName(first);/store first namesetLastName(last);/store last namesetMonthlySalary(salary);/validate and store monthly salary /end E mp l
33、oyee constructor/set first namevoid E mp loyee:setF irstName(string name)(firstName=name;/no validation needed /end function setF irstName/return first namestring E mp loyee:g etF irstNameO(return firstName;/end function g etF irstName/set last namevoid E mp loyee:setLastName(string name)lastName=na
34、me;/no validation needed /end function setLastName/return last namestring Employee:getLastName()(return lastName;/end function getLastName/set monthly salary;if not positive,set to 0.0void Employee:setMonthlySalary(int salary)(if(salary 0)/if salary is positivemonthlySalary=salary;/set monthlySalary
35、 to salaryif(salary=0)/if salary is not positivemonthlySalary=0;/set monthlySalary to 0.0 /end function setMonthlySalary/return monthly salaryint Employee:getMonthlySalary()(return monthlySalary;/end function getMonthlySalary测试函数:#include using std:cout;using std:endl;#include“Employee,h/include def
36、inition of class Employee/function main begins program executionint main()(/create two Employee objectsEmployee employeel(Lisa,Roberts”,4500);Employee employee2(Mark,Stein”,4000);/display each Employee,s yearly salarycout ”Employees yearly salaries:endl;/retrieve and display employeeT s monthly sala
37、ry multiplied by 12int monthlySalaryl=employeel.getMonthlySalary();cout employeel.getFirstName()employeel.getLastName()“:$monthlySalaryl*12 endl;/retrieve and display employee2,s monthly salary multiplied by 12int monthlySalary2 =employee2.getMonthlySalary();cout employee2.getFirstName()”“employee2.
38、getLastName()“:$monthlySalary2 *12 endl;/give each Employee a 10%raiseemployeel.setMonthlySalary(monthlySalaryl*1.1);emp loyee2.setMonthlySalary(monthlySalary2*1.1);/disp lay each E mp loyee,s yearly salary ag aincout nE mp loyees,yearly salaries after 10%raise:endl;/retrieve and disp lay emp loyeeT
39、 s monthly salary multip lied by 12monthlySalaryl 二 emp loyeel.g etMonthlySalary();cout emp loyeel.g etF irstName()“emp loyeel.g etLastName()“:$monthlySalaryl*12 endl;monthlySalary2=emp loyee2.g etMonthlySalary();cout emp loyee2.g etF irstName()emp loyee2.g etLastName()“:$monthlySalary2*12 endl;retu
40、rn 0;/indicate successful termination /end main3.15类定义:class Date(p ublic:Date(int,int,int);/constructor initializes data membersvoid setMonth(int);/set monthint g etMonth();/return monthvoid setDay(int);/set dayint g etDay();/return dayvoid setYear(int);/set yearint g etYear();/return yearvoid disp
41、 layDateO;/disp lays date in mm/dd/yyyy formatp rivate:int month;/the month of the dateint day;/the day of the dateint year;/the year of the date);/end class Date类成员函数:#include using std:cout;using std:endl;include Date h/include definition of class Date from Date,h/Date constructor that initializes
42、 the three data members;/assume values p rovided are correct(really should validate)Date:Date(int m,int d,int y)(setMonth(m);setDay(d);setYear(y);/end Date constructor/set monthvoid Date:setMonth(int m)(month=m;if(month 12 )month=1;/end function setMonth/return monthint Date:getMonth()(return month;
43、/end function getMonth/set dayvoid Date:setDay(int d)(day=d;/end function setDay/return dayint Date:getDay()(return day;/end function getDay/set yearvoid Date:setYear(int y)(year=y;/end function setYear/return yearint Date:getYear()(return year;/end function getYear/print Date in the format mm/dd/yy
44、yyvoid Date:displayDate()(cout month /day /year endl;/end function displayDate测试函数:include using std:cout;using std:endl;include Dateh/include definition of class Date from Date,h/function main begins program executionint mainODate date(5,6,19 8 1);/create a Date object for May 6,19 8 1/disp lay the
45、 values of the three Date data memberscout ”Month:date.g etMonth()endl;cout Day:date.g etDay()endl;cout Year:date.g etYear()endl;cout XnOrig inal date:endl;date.disp layDateO;/outp ut the Date as 5/6/19 8 1/modify the Datedate.setMonth(13);/invalid monthdate.setDay(1);date.setYear(2005);cout ”nNew d
46、ate:endl;date.disp layDateO;/outp ut the modified date(1/1/2005)return 0;/indicate successful termination /end main9.05类定义:ttifndef C0MPLE X_Httdefine C0MPLE X_Hclass Comp lex(p ublic:Comp lex(double=0.0,double=0.0);/default constructorComp lex add(const Comp lex&);/function addComp lex subtract(con
47、st Comp lex&);/function subtractvoid p rintComp lex();/p rint comp lex number formatvoid setComp lexNumber(double,double);/set comp lex numberp rivate:double realPart;double imag inaryPart;/end class Comp lexftendif类成员函数:#include using std:cout;#include Comp lex,h”Comp lex:Comp lex(double real,doubl
48、e imag inary)(setComp lexNumber(real,imag inary);/end Comp lex constructorComp lex Comp lex:add(const Comp lex ferig ht)return Complex(realPart+right.realPart,imaginaryPart+right.imaginaryPart);/end function addComplex Complex:subtract(const Complex&right)(return Complex(realPart-right.realPart,imag
49、inaryPart-right.imaginaryPart);/end function subtractvoid Complex:printComplex()(cout (realPart ”,imaginaryPart ;/end function printComplexvoid Complex:setComplexNumber(double rp,double ip)(realPart=rp;imaginaryPart=ip;/end function setComplexNumber测试函数:include using std:cout;using std:endl;#include
50、 Complex,h”int main()(Complex a(1,7),b(9,2 ),c;/create three Complex objectsa.printComplex();/output object acout +;b.printComplex();/output object bcout =;c=a.add(b);/invoke add function and assign to object cc.printComplex();/output object ccout n,;a.setComplexNumber(10,1);/reset realPart andb.set