




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Chapter 10DEFINING CLASSES AND ABSTRACT DATA TYPES1. Solutions for and Remarks on Selected Programming Problems This chapter can be done after Chapter 7, Arrays. However, I have not used anything from that chapter in these solutions. Several of these solutions could be simplified in good measure if
2、arrays were used instead of the extensive switch and nested if else statements.1. Class grading programI have put statements of programming strategy and of the problem in the program comments.Onestruct StudentRecordint studentNumber;double quiz1;double quiz2;double midterm;double final;double averag
3、e;char grade;void input(StudentRecord& student);void computeGrade(StudentRecord& student);void output(const StudentRecord student);int main()StudentRecord studentCLASS_SIZE;for(int i = 0; i CLASS_SIZE; i+) input(studenti); ;cout endl endl;void computeGrade(StudentRecord& student) n;abort();= letterG
4、radeindex;void output(const StudentRecord student)cout The record for student number: endl The quiz grades are: I! I! endl The midterm and exam grades are: endl The numeric average is: endl and the letter grade assigned is endl;Data for the test run:1 7 10 90 952 9 8 90 803 7 8 70 804 5 8 50 705 4 0
5、 40 35Command line command to execute the text run:ch10prg1 dataOutput:enter the student number: 1enter two 10 point quizes7 10enter the midterm and final exam grades. These are 100 point tests 90 95enter the student number: 2enter two 10 point quizes9 8enter the midterm and final exam grades. These
6、 are 100 point tests 90 80enter the student number: 3enter two 10 point quizes7 8enter the midterm and final exam grades. These are 100 point tests 70 80enter the student number: 4enter two 10 point quizes5 8enter the midterm and final exam grades. These are 100 point tests 50 70enter the student nu
7、mber: 5enter two 10 point quizes4 0enter the midterm and final exam grades. These are 100 point tests 40 35The record for student number: 1The quiz grades are: 7 10The midterm and exam grades are: 90 95The numeric average is:and the letter grade assigned is AThe record for student number: 2The quiz
8、grades are: 9 8The midterm and exam grades are: 90 80The numeric average is:and the letter grade assigned is BThe record for student number: 3The quiz grades are: 7 8The midterm and exam grades are: 70 80The numeric average is:and the letter grade assigned is CThe record for student number: 4The qui
9、z grades are: 5 8The midterm and exam grades are: 50 70The numeric average is:and the letter grade assigned is DThe record for student number: 5The quiz grades are: 4 0The midterm and exam grades are: 40 35The numeric average is:and the letter grade assigned is F*/2. Redefine CDAccount from Display
10、to be a class rather than struct. Use the same variables, make them private.Add member functions:to return initial balanceto return balance at maturity to return interest rate to return the term default constructor constructor to set specified values input function (istream&); output function (ostre
11、am&);Embed in a test programThe code in Display makes the behavior of the required functions clear.Note on capitalization schemes:I use a slightly differentcapitalization scheme than the author. You should make your conventions clear to the student. Any capitalization that produces readable code is
12、acceptable to this author. The instructor, as always, is left free to do as is wished.CD account, different interfaceRedo the definition of class CDAccount from Project 2 so that the interface is the same but the implementation is different. The new implementation is similar to the second implementa
13、tion of BankAccount in Display . Here the balance is recorded in two int values, one for dollars, one for cents. The member variable for interest rate stores the interest as a fraction rather than a percentage. Term is stored as in Project 2.Remark: The changes to be made are in the functions that t
14、ake balance as argument. The implementation of the members must change:1) to generate the int objects dollars and cents from the external representation of balance (a double)2) to take dollars and cents (int objects) from the internal representation and generate the external information. interest ra
15、te is a double (decimal) fraction rather term is stored the same#include using namespace std;class CDAccountpublic:CDAccount();CDAccount(double bal, double intRate, int T ); double InterestRate();double InitialBalance();double BalanceAtMaturity();int Term();void input(istream&);void output(ostream&)
16、;private:No Answer Provided5. No Answer Provided6. Class MonthHere we create an abstract data type to represent month.The class month has the following member functions:a constructor to set month based on the first 3 letters of the name (uses 3 char args)a constructor to set month base on month numb
17、er, 1 = January etc. a default constructor (what does it do?)an input function to set the month based on the month number an input function to set the month based on a three-character input an output function that outputs the month as an integer, an output function that outputs the month as the lett
18、ers.a function that returns the next month as a Month objectNB each input and output function have a single formal parameter for the streamData store is an int object.notThis problem doesnt say anything about error checking. It is easy and (I hope) obvious how to do error checking. I will require my
19、 students put it in, and I use it here. The careful reader will note that testing is thorough. It is an excellent exercise to provide test data that makes coverage complete. (Complete coverage is to test all possible paths through the program.)With these comments, here is the code a the solution to
20、the problem: #include Month();Month nextMonth(); This access member added forNot neede in this problemint Month:monthNumber()return mnth;Month Month:nextMonth()int nextMonth = mnth + 1; if (nextMonth = 13) nextMonth = 1;return Month(nextMonth);Month:Month( int monthNumber)mnth = monthNumber;void Mon
21、th:outputMonthNumber( ostream& in ) void Month:outputMonthName(ostream& out) We dont have one yet. if (1 = mnth) out Jan;else if (2 = mnth) out Feb;else if (3 = mnth) out Mar;else if (4 = mnth) out Apr; else if (5 = mnth) out May;else if (6 =mnth) out Jun ;else if (7 =mnth) out Jul ;else if (8 =mnth
22、) out Aug;else if (9 =mnth) out Sep;else if (10 = mnth) out Oct;else if (11 = mnth) out Novelse if (12 = mnth) out Decvoid error(char c1, char c2, char c3)cout endl c1 c2 c3 is not a month. Exitingn; exit(1);void error(int n)cout endl n is not a month number. Exiting mnth;void Month:getMonthByName(i
23、stream& in).) which exits, if the month name is wrong. char c1, c2, c3;in c1 c2 c3;c1 = tolower(c1);int main()cout testing constructor Month(char, char, char) endl; Month m;m = Month( j, a, n);( cout ); cout ;(cout); cout endl;m = Month( f, e, b);( cout ); cout ;(cout); cout endl;m = Month( m, a, r)
24、;( cout ); cout ;(cout); cout endl;m = Month( a, p, r);( cout ); cout ;(cout); cout endl;m = Month( m, a, y);( cout ); cout ;(cout); cout endl;m = Month( j, u, n);( cout ); cout ;(cout); cout endl; m = Month( j, u, l);( cout ); cout ;(cout); cout endl; m = Month( a, u, g);( cout ); cout ;(cout); cou
25、t endl;m = Month( s, e, p);( cout ); cout ;(cout); cout endl;m = Month( o, c, t);( cout ); cout ;(cout); cout endl;m = Month( n, o, v);( cout ); cout ;(cout); cout endl;m = Month( d, e, c);( cout ); cout ;(cout); cout endl;cout endl Testing Month(int) constructor endl; int i = 1;while (i = 12)Month
26、mm(i);( cout ); cout ;(cout); cout endl;i = i+1;cout endl Testing the getMonthByName and outputMonth* n; i = 1;Month mm;while (i = 12)(cin);( cout ); cout ;(cout); cout endl;i = i+1;cout endl Testing getMonthByNumber and outputMonth* endl; i = 1; while (i = 12) (cin);(cout); cout ;(cout); cout endl;
27、i = i+1;cout endl end of loops endl;cout endl Testing nextMonth member endl;cout current month ;(cout); cout endl; cout next month ;().outputMonthNumber(cout); cout ; ().outputMonthName(cout); cout endl;cout endl new Month created endl; Month mo(6);cout current month ;(cout); cout endl; cout nextMon
28、th ;().outputMonthNumber(cout); cout ; ().outputMonthName(cout); cout endl; return 0;/*A testing run follows:$testing constructor Month(char, char, char)1 Jan2 Feb3 Mar4 Apr5 May6 Jun7 Jul8 Aug9 Sep10 Oct11 Nov12 DecTesting Month(int) constructor1 Jan*/7. Redefine the implementation of class Month f
29、rom #6.Store the month as 3 chars.Remarks: This will cause a permutation of the code in the various functions. Where in #5 we had to generate a month number from a three letter month name in a member function and in a constructor, here we will need to have this code in functions that tell us the mon
30、th as an integer. Input functions such as getMonthByNumber, the constructor Month(int) will have to have table lookup to generate the three characters.8. Rewrite program from DisplayRewrite program from Display but use class Month from #5 or #6 as the type of the member variable to record the month.
31、 Redefine the member function output so that it has one formal parameter of type ostream.Cause all output to the screen to be also written to a file. Input is still from keyboard. Only the output is sent to a file.I have marked the start and endThis#include #include #include #include using namespace
32、 std;class DayOfYearpublic:void input(); void set(int newMonth, int newDay);int getMonth(); .12 = Decint getDay(); . endl;();cout Todays date is ;outStream Todays date is ;(cout);cout endl;(outStream);outStream endl;( 3, 21);cout . Bachs birthday is ; outStream . Bachs birthday is ;(cout);cout endl;
33、(outStream); outStream endl;if ( () = ()& () = () )cout Happy Birthday Johann Sebastian! endl; outStream Happy Birthday Johann Sebastian! endl;elsecout Happy Unbirthday Johann Sebastian! endl; outStream Happy Unbirthday Johann Sebastian! endl;();return 0;void DayOfYear:input()cout Enter the month as
34、 a number: I added an access member toEnter the month as a number: 4Enter the day of the month: 5Todays date is Apr, 5. Bachs birthday is Mar, 21Happy Unbirthday Johann Sebastian! 17:36:19:/AW$ catTodays date is Apr, 5. Bachs birthday is Mar, 21Happy Unbirthday Johann Sebastian! 17:36:23:/AW$A secon
35、d run:17:37:19:/AW$Enter todays date.Enter the month as a number: 3Enter the day of the month: 21Todays date is Mar, 21. Bachs birthday is Mar, 21Happy Birthday Johann Sebastian! 17:37:29:/AW$ catTodays date is Mar, 21. Bachs birthday is Mar, 21Happy Birthday Johann Sebastian! 17:37:35:/AW$9.“ The L
36、ittle Red Grocery Store Cou nter”One might start with the soluti on to #4 in solv ing this one.The class cou nter should provide:A default con structor. For example, Coun ter(9999); provides a cou nter that can cou nt up to9999 and displays 0.A member fun ctio n, void reset() that returns count to 0
37、A set of fun cti ons that in creme nt digits 1 through 4: void in cr1()A member fun cti on bool overflow。; detects overflow.Use the class to simulate the little red grocery store money cou nter.Display the 4 digits, the right most two are cents and tens of cen ts, the n ext to aredollars and tens of
38、 dollars.Provide keys for in creme nti ng cen ts, dimes, dollars and tens of dollars.Suggesti on: asdfo: a for cen ts, followed by 1-9s for dimes, followed by 1-9d for dollars, followed by 1-9f for tens of dollars, followed by 1-9Followed by press ing the return key in each case.Addi ng is automatic
39、, and overflow is reported after each operati on. Overflow can be requested with the O key.Here is a tested impleme ntati on of this simulati on. I do not supply output. You will probably n eed to adjust the PAUSE_CONSTANT for your machi ne, otherwise the pause can be so short as to be useless, or i
40、rritati ngly long.#in clude using n amespace std;const int PAUSE_CONSTANT = 0; RESULTS ARE NOT RELIABLE. Press Q to quit.n; cout endl;(); ();cout .;(); ();cout endl;cout Enter a character followed by a digit 1-9:n Enter a for unitsn s for tensn d for hundredsn f for thousandsn o to inquire about ove
41、rflown ch;Quittingn; return 0;if(ch = o) cout Overflow test requestedn;if()cout OVERFLOW HAS OCCURRED. RESULTS j;default: cout Program should never get heren Fix programn;abort();cout At end of switch n;return 0;. .n;for(int X = 0; X PAUSE_CONSTANT; X+)X+; X-;void Counter:displayUnits()cout units;vo
42、id Counter:displayTens()cout tens;void Counter:displayHundreds()cout hundreds;void Counter:displayThousands()cout thousands;void Counter:reset()units = tens = hundreds = thousands = 0;overflowFlag = false;void Counter:display()cout thousands hundreds tens units ;bool Counter:overflow()return overflo
43、wFlag;Counter:Counter():units(0), tens(0), hundreds(0), thousands(0), overflowFlag(false) Rational Number ClassThe one member function I would add is a“reduce ” member function. Thisfunction should compute the greatest common divisor (GCD) of thenumerator and denominator, then divide each by this nu
44、mber. This will reduce the fraction to lowest common terms. If this is not done, the numerator and denominator can grow, possibly far enough to cause integer overflow for int variables.Sequence for writing the member functions:The idea here is“ Code in small increments then test.”Write the construct
45、ors of several kinds.Write an access function for the real and imaginary parts to test the constructors.TEST.Write the less and neg functions.TESTIf you plan to write the reduce function, do it now.TEST.Write the output and input member functions.TESTWrite the arithmetic functions, one at a time , a
46、nd call the reduce function after the these functions have done their work, before returning the caller.TEST.11. endl;(50);cout After another 50 miles, () gallons used. endl;cout endl;();(13);(100);cout For your gas guzzler: endl;cout After 100 miles, () gallons used. endl;(50);cout After another 50
47、 miles, () gallons used. endl;return 0;2. Outline of Topics in the ChapterStructuresStructures for Diverse DataStructures as Function ArgumentsInitializing StructureClassesDefining Classes and Member FunctionsPublic and Private MembersSummary of Some Properties of ClassesConstructors for Initializat
48、ionAbstract Data TypesClasses to Produce ADTs3. General Remarks on the ChapterChapter Flexibility: This book is designed with flexibility in mind. Chapter 3, More Flow of Control, can be covered before Chapter 10 if desired. The solutio ns to the program ming projects are done with this in mind, and
49、 either solutio ns are provided that are in depe ndent of the other chapter or notes are provided on how to transform the solution.Prior to this chapter, we have seen the words class and object. We have see n examples of classes and objects, but we have not see n the tools to define classes. That is
50、 the subject matter of this chapter.Structures (keyword: struct)Historical note: The name struct in C+ is provided primarily for backward compatibility with ANSI C. (Every pro-gram in Kerni gha n and Ritchie, The C Program ming Lan guage, sec ond editi on, is a correct C+ program .In fact, the autho
51、rs checked the code while writ ing that book using an early C+ compiler.) The author points out that two identifiers that are declared with the same structure type may be assig ned, where member wise assignment Memberwise assig nment is madefrom the r-value member to the l-value member in thecorresp
52、 onding positi on. The two objects are defi ned with the same structure tag so members in corresp onding positi ons will have the same type. We will see that differe nt classes can have differing assignment definitions. The assignment that occurs is the type defi ned for the type of the member. We w
53、ill see in a later chapter that thisdefault assignment mechanism is the only one the compiler can always know how to do, and may well not be what the programmer should use. occurs. The critical point here is that the two structure identifiers be declared with the same struct tag. In the example that follows, the types are in dist in guishab
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年医保知识考试题库及答案:医保政策调整与影响实务应用与法规试题
- 2025年中学教师资格考试《综合素质》教师职业道德与教育教学改革试题(含答案)
- 2025年中学教师资格考试《综合素质》教师职业道德知识试题及答案集
- 容器化环境下的测试用例验证-洞察及研究
- 知柏地黄丸与现代降糖药物联合治疗慢性肾炎的协同效应研究-洞察及研究
- 动态调整策略在创新网络管理中应用-洞察及研究
- 精准口腔碘液在牙齿修复与维护中的研究进展-洞察及研究
- 细胞周期调控与肿瘤抑制-洞察及研究
- 八珍益母膏对改善女性心理健康的作用研究-洞察及研究
- GB/T 46087.3-2025车间底漆焊接及相关工艺试验第3部分:热切割
- 2026届房山区高三开学考试语文试题及参考答案
- 珠海市金湾区园洲岛海洋牧场养殖区项目环境影响报告书
- 街道社区安全培训内容课件
- 桡骨骨折复位内固定术
- 上海银行面试实战经验分享:面试题库解读求职者必看
- 2025至2030年中国办公设备租赁行业市场深度分析及发展前景预测报告
- 六分钟步行试验:慢性心力衰竭患者临床诊疗的多维度应用与探索
- 急性呼吸衰竭患者的急救与护理
- 快递月末工作汇报
- 配电箱安全管理制度
- 棉纱库存管理办法
评论
0/150
提交评论