版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、Chapter 11Friends, Overloaded Operators,and Arrays in ClassesOverview11.1 Friend Functions 11.2 Overloading Operators11.3 Arrays and Classes11.4 Classes and Dynamic ArraysSlide 11- 311.1Friend FunctionsFriend FunctionClass operations are typically implementedas member functionsSome operations are be
2、tter implemented as ordinary (nonmember) functionsSlide 11- 5Program Example:An Equality FunctionThe DayOfYear class from Chapter 10 canbe enhanced to include an equality functionAn equality function tests two objects of type DayOfYear to see if their values represent the same dateTwo dates are equa
3、l if they represent the same day and monthSlide 11- 6Declaration of The equality FunctionWe want the equality function to return a valueof type bool that is true if the dates are the sameThe equality function requires a parameter foreach of the two dates to compareThe declaration is bool equal(DayOf
4、Year date1, DayOfYear date2);Notice that equal is not a member of the class DayOfYearSlide 11- 7Defining Function equalThe function equal, is not a member functionIt must use public accessor functions to obtain the day and month from a DayOfYear objectequal can be defined in this way:bool equal(DayO
5、fYear date1, DayOfYear date2) return ( date1.getMonth( ) = date2.getMonth( ) & date1.getDay( ) = date2.getDay( ) ); Slide 11- 8Using The Function equalThe equal function can be used to compare datesin this manner if ( equal( today, bach_birthday) ) cout Its Bachs birthday!;A complete program using f
6、unction equal is found in Slide 11- 9Display 11.1 (1)Display 11.1 (2)Display 11.1 (3)Is equal Efficient?Function equal could be made more efficientEqual uses member function calls to obtain the private data valuesDirect access of the member variables would be more efficient (faster)Slide 11- 10A Mor
7、e Efficient equalAs defined here, equal is more efficient,but not legal bool equal(DayOfYear date1, DayOfYear date2) return (date1.month = = date2.month & date1.day = = date2.day ); The code is simpler and more efficientDirect access of private member variables is not legal!Slide 11- 11Friend Functi
8、onsFriend functions are not members of a class, butcan access private member variables of the classA friend function is declared using the keywordfriend in the class definitionA friend function is not a member functionA friend function is an ordinary functionA friend function has extraordinary acces
9、s to data members of the classAs a friend function, the more efficient version of equal is legalSlide 11- 12Declaring A FriendThe function equal is declared a friend in the abbreviated class definition here class DayOfYear public: friend bool equal(DayOfYear date1, DayOfYear date2); / The rest of th
10、e public members private: / the private members ;Slide 11- 13Using A Friend FunctionA friend function is declared as a friend in the class definitionA friend function is defined as a nonmember function without using the : operatorA friend function is called without using the . operatorSlide 11- 14Di
11、splay 11.2Friend Declaration SyntaxThe syntax for declaring friend function is class class_name public: friend Declaration_for_Friend_Function_1 friend Declaration_for_Friend_Function_2 Member_Function_Declarations private: Private_Member_Declarations ;Slide 11- 15Are Friends Needed?Friend functions
12、 can be written as non-friendfunctions using the normal accessor and mutator functions that should be part of the classThe code of a friend function is simpler and it ismore efficientSlide 11- 16Choosing FriendsHow do you know when a function should be a friend or a member function?In general, use a
13、 member function if the task performed by the function involves only one objectIn general, use a nonmember function if the taskperformed by the function involves more thanone objectChoosing to make the nonmember function a friend isa decision of efficiency and personal tasteSlide 11- 17Program Examp
14、le:The Money Class (version 1)Display 11.3 demonstrates a class called MoneyU.S. currency is representedValue is implemented as an integer representing the value as if converted to penniesAn integer allows exact representation of the valueType long is used to allow larger valuesTwo friend functions,
15、 equal and add, are usedSlide 11- 18Display 11.3 (1 5)Characters to IntegersNotice how function input (Display 11.3)processes the dollar values enteredFirst read the character that is a $ or a If it is the -, set the value of negative to true and read the $ sign which should be nextNext read the dol
16、lar amount as a longNext read the decimal point and cents as three charactersdigitToInt is then used to convert the cents characters to integersSlide 11- 19digitToInt (optional)digitToInt is defined as int digitToInt(char c) return ( static_cast ( c ) static_cast( 0) ); A digit, such as 3 is paramet
17、er cThis is the character 3 not the number 3The type cast static_cast(c) returns the number that implements the character stored in cThe type cast static_castint(0) returns the number that implements the character 0Slide 11- 20int( c) int (0)?The numbers implementing the digits are in in orderint(0)
18、 + 1 is equivalent to int(1)int(1) + 1 is equivalent to int(2)If c is 0int( c ) - int(0) returns integer 0If c is 1int( c ) int (0) returns integer 1Slide 11- 21Leading ZerosSome compilers interpret a number with a leading zero as a base 8 numberBase 8 uses digits 0 7Using 09 to represent 9 cents co
19、uld cause an error the digit 9 is not allowed in a base 8 numberThe ANSI C+ standard is that input should be interpreted as base 10 regardless of a leading zeroSlide 11- 22Parameter Passing EfficiencyA call-by-value parameter less efficient than acall-by-reference parameterThe parameter is a local v
20、ariable initialized to the value of the argumentThis results in two copies of the argument A call-by-reference parameter is more efficientThe parameter is a placeholder replaced by the argumentThere is only one copy of the argument Slide 11- 23Class ParametersIt can be much more efficient to use cal
21、l-by-reference parameters when the parameteris of a class typeWhen using a call-by-reference parameter If the function does not change the value of the parameter, mark the parameter so the compiler knows it should not be changedSlide 11- 24const Parameter ModifierTo mark a call-by-reference paramete
22、r so it cannot be changed:Use the modifier const before the parameter typeThe parameter becomes a constant parameterconst used in the function declaration and definitionSlide 11- 25const Parameter ExampleExample (from the Money class of Display 11.3): A function declaration with constant parametersf
23、riend Money add(const Money& amount1, const Money& amount2); A function definition with constant parametersMoney add(const Money& amount1, const Money& amount2) Slide 11- 26const ConsiderationsWhen a function has a constant parameter,the compiler will make certain the parametercannot be changed by t
24、he functionWhat if the parameter calls a member function? Money add(const Money& amount1, const Money& amount2) amount1.input( cin ); The call to input will change the value of amount1!Slide 11- 27const And Accessor FunctionsWill the compiler accept an accessor function call from the constant parame
25、ter? Money add(const Money& amount1, const Money& amount2) amount1.output(cout); The compiler will not accept this codeThere is no guarantee that output will not change the value of the parameterSlide 11- 28const Modifies FunctionsIf a constant parameter makes a member functioncallThe member functio
26、n called must be marked so the compiler knows it will not change the parameterconst is used to mark functions that will not changethe value of an objectconst is used in the function declaration and thefunction definitionSlide 11- 29Function DeclarationsWith constTo declare a function that will not c
27、hange the value of any member variables:Use const after the parameter list and just before the semicolonclass Money public: void output (ostream& outs) const ; Slide 11- 30Function Definitions With constTo define a function that will not change the value of any member variables:Use const in the same
28、 location as the function declaration void Money:output(ostream& outs) const / output statementsSlide 11- 31const Problem SolvedNow that output is declared and defined usingthe const modifier, the compiler will accept this codeMoney add(const Money& amount1, const Money& amount2) amount1.output(cout
29、); Slide 11- 32const WrapupUsing const to modify parameters of class typesimproves program efficiencyconst is typed in front of the parameters type Member functions called by constant parametersmust also use const to let the compiler know they do not change the value of the parameterconst is typed f
30、ollowing the parameter list in the declaration and definitionSlide 11- 33Display 11.4Use const ConsistentlyOnce a parameter is modified by using const to make it a constant parameterAny member functions that are called by the parameter must also be modified using const to tell the compiler they will
31、 not change the parameterIt is a good idea to modify, with const, every member function that does not change a member variableSlide 11- 34Section 11.1 ConclusionCan youDescribe the promise that you make to the compiler when you modify a parameter with const?Explain why this declaration is probably n
32、ot correct?class Money public: void input(istream& ins) const; ; Slide 11- 3511.2Overloading OperatorsOverloading OperatorsIn the Money class, function add was used to add two objects of type MoneyIn this section we see how to use the + operatorto make this code legal:Money total, cost, tax;total =
33、cost + tax; / instead of total = add(cost, tax);Slide 11- 37Operators As FunctionsAn operator is a function used differently thanan ordinary functionAn ordinary function call enclosed its arguments in parenthesis add(cost, tax)With a binary operator, the arguments are on eitherside of the operator c
34、ost + taxSlide 11- 38Operator OverloadingOperators can be overloadedThe definition of operator + for the Money class is nearly the same as member function addTo overload the + operator for the Money classUse the name + in place of the name addUse keyword operator in front of the + Example:friend Mon
35、ey operator + (const Money& amount1Slide 11- 39Operator Overloading RulesAt least one argument of an overloaded operator must be of a class typeAn overloaded operator can be a friend of a classNew operators cannot be createdThe number of arguments for an operator cannotbe changedThe precedence of an
36、 operator cannot be changed., :, *, and ? cannot be overloadedSlide 11- 40Program Example:Overloading Operators The Money class with overloaded operators+ and = is demonstrated in Slide 11- 41Display 11.5 (1)Display 11.5 (2)Automatic Type ConversionWith the right constructors, the system can dotype
37、conversions for your classesThis code (from Display 11.5) actually works Money baseAmount(100, 60), fullAmount; fullAmount = baseAmount + 25;The integer 25 is converted to type Money so it can be added to baseAmount!How does that happen?Slide 11- 42Type Conversion Event 1When the compiler sees baseA
38、mount + 25, it first looks for an overloaded + operator to perform MoneyObject + integerIf it exists, it might look like thisfriend Money operator +(const Money& amount1, const int& amount2);Slide 11- 43Type Conversion Event 2When the appropriate version of + is not found, the compiler looks for a c
39、onstructor that takes a single integerThe Money constructor that takes a single parameterof type long will work The constructor Money(long dollars) converts 25 to a Money object so the two values can be added!Slide 11- 44Type Conversion AgainAlthough the compiler was able to find a way to add baseAm
40、ount + 25this addition will cause an error baseAmount + 25.67There is no constructor in the Money class that takes a single argument of type doubleSlide 11- 45A Constructor For doubleTo permit baseAmount + 25.67, the following constructor should be declared and definedclass Money public: Money(doubl
41、e amount); / Initialize object so its value is $amount Slide 11- 46Overloading Unary OperatorsUnary operators take a single argumentThe unary operator is used to negate a value x = -y+ and - - are also unary operatorsUnary operators can be overloadedThe Money class of Display 11.6 can includes A bin
42、ary operatorA unary operator Slide 11- 47Overloading -Overloading the operator with two parametersallows us to subtract Money objects as in Money amount1, amount2, amount2; amount3 = amount1 amount2;Overloading the operator with one parameterallows us to negate a money value like this amount3 = -amo
43、unt1;Slide 11- 48Display 11.6Overloading The insertion operator is a binary operatorThe first operand is the output streamThe second operand is the value following cout Hello out there.n;Slide 11- 49Operand 1OperatorOperand 2Replacing Function outputOverloading the operator allows us to use instead
44、of Moneys output functionGiven the declaration: Money amount(100); amount.output( cout ); can become cout amount;Slide 11- 50What Does Return?Because is a binary operator cout I have amount in my purse.; seems as if it could be grouped as( (cout I have ) amount) in my purse.;To provide cout as an ar
45、gument for amount,(cout I have) must return coutSlide 11- 51Display 11.7Overloaded DeclarationBased on the previous example, should returnits first argument, the output streamThis leads to a declaration of the overloaded operator for the Money class: class Money public: friend ostream& operator (ost
46、ream& outs, const Money& amount); Slide 11- 52Overloaded DefinitionThe following defines the operatorostream& operator (ostream& outs, const Money& amount) return outs; Slide 11- 53Return ostream& ?The & means a reference is returnedSo far all our functions have returned valuesThe value of a stream
47、object is not so simple to returnThe value of a stream might be an entire file, the keyboard, or the screen!We want to return the stream itself, not the value of the streamThe & means that we want to return the stream, not its valueSlide 11- 54Overloading Overloading the operator for input is very s
48、imilar to overloading the could be defined this way for the Money class istream& operator (istream& ins, Money& amount); return ins; Slide 11- 55Display 11.8 (1-4)Section 11.2 ConclusionCan youDescribe the purpose of a making a function a friend?Describe the use of constant parameters?Identify the r
49、eturn type of the overloaded operators?Slide 11- 5611.3Arrays and ClassesArrays and ClassesArrays can use structures or classes as their base typesExample: struct WindInfo double velocity; char direction; WindInfo dataPoint10;Slide 11- 58Accessing MembersWhen an arrays base type is a structure or a
50、classUse the dot operator to access the members of anindexed variableExample: for (i = 0; i 10; i+) cout dataPointi.velocity; Slide 11- 59An Array of MoneyThe Money class of Chapter 11 can be the basetype for an arrayWhen an array of classes is declaredThe default constructor is called to initialize
51、 the indexed variablesAn array of class Money is demonstrated in Slide 11- 60Display 11.9 (1-2)Arrays as Structure MembersA structure can contain an array as a memberExample: struct Data double time10; int distance; Data myBest;myBest contains an array of type doubleSlide 11- 61Accessing Array Eleme
52、ntsTo access the array elements within a structureUse the dot operator to identify the array within the structureUse the s to identify the indexed variable desiredExample: myBest.timeireferences the ith indexed variable of the variable time in the structure myBestSlide 11- 62Arrays as Class MembersC
53、lass TemperatureList includes an arrayThe array, named list, contains temperaturesMember variable size is the number of items stored class TemperatureList public: TemperatureList( ); /Member functions private: double list MAX_LIST_SIZE; int size; Slide 11- 63Overview of TemperatureListTo create an o
54、bject of type TemperatureList:TemperatureList myData;To add a temperature to the list:myData.add_temperature(77);A check is made to see if the array is full is overloaded so output of the list iscout myData;Slide 11- 64Display 11.10 (1-2)Section 11.3 ConclusionCan youDeclare an array as a member of
55、a class?Declare an array of objects of a class?Write code to call a member function of an element in an array of objects of a class?Write code to access an element of an array of integers that is a member of a class?Slide 11- 6511.4Classes and Dynamic ArraysClasses and Dynamic Arrays A dynamic array
56、 can have a class as its base typeA class can have a member variable that is adynamic arrayIn this section you will see a class using a dynamic array as a member variable.Slide 11- 67Program Example:A String Variable ClassWe will define the class StringVarStringVar objects will be string variablesSt
57、ringVar objects use dynamic arrays whose size is determined when the program is runningThe StringVar class is similar to the string class discussed earlierSlide 11- 68The StringVar ConstructorsThe default StringVar constructor creates an object with a maximum string length of 100Another StringVar co
58、nstructor takes an argumentof type int which determines the maximumstring length of the objectA third StringVar constructor takes a C-stringargument andsets maximum length to the length of the C-stringcopies the C-string into the objects string valueSlide 11- 69The StringVar InterfaceIn addition to
59、constructors, the StringVar interface includes:Member functionsint length( );void input_line(istream& ins);friend ostream& operator (ostream& outs, const StringVar& theString);Copy Constructor discussed laterDestructor discussed laterSlide 11- 70Display 11.11 (1)Display 11.11 (2)A StringVar Sample P
60、rogramUsing the StringVar interface of Display 11.11,we can write a program using the StringVar classThe program uses function conversation toCreate two StringVar objects, yourName and ourNameyourName can contain any string MAX_NAME_SIZE or shorter in lengthourName is initialized to Borg and can hav
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 贛南師范大學(xué)科技學(xué)院《幼兒心理學(xué)》2023-2024學(xué)年第一學(xué)期期末試卷
- 贛南師范大學(xué)《服裝材料》2023-2024學(xué)年第一學(xué)期期末試卷
- 七年級(jí)生物上冊(cè)第二單元第一章第二節(jié)植物細(xì)胞教案新版新人教版
- 三年級(jí)數(shù)學(xué)比較分?jǐn)?shù)的大小課件
- 三年級(jí)科學(xué)下冊(cè)第三單元固體和液體4把液體倒進(jìn)水里去教案蘇教版1
- 小學(xué)生課堂提問制度
- 綜合核算培訓(xùn)課件
- 三年級(jí)數(shù)學(xué)認(rèn)識(shí)噸課件
- 麻醉藥品、第一類精神藥品安全管理制度
- 《水準(zhǔn)測(cè)量和水準(zhǔn)儀》課件
- OpenCV計(jì)算機(jī)視覺基礎(chǔ)教程(Python版)教學(xué)教案
- 2024年度二人合伙光伏發(fā)電項(xiàng)目投資合同3篇
- 《涉江采芙蓉》 課件高中語文統(tǒng)編版必修上冊(cè)
- 管道護(hù)理小組工作總結(jié)
- 北京市西城區(qū)2023-2024學(xué)年六年級(jí)上學(xué)期數(shù)學(xué)期末試卷(含答案)
- 幼兒園繪本故事《三只小豬蓋房子》教學(xué)課件全文
- 人臉識(shí)別項(xiàng)目施工方案方案
- 北京市房山區(qū)2023-2024學(xué)年九年級(jí)上學(xué)期期末語文試題(解析版)
- 15《八角樓上》說課稿-2024-2025學(xué)年語文二年級(jí)上冊(cè)(統(tǒng)編版)
- 施工工地汛期防洪防汛應(yīng)急預(yù)案(9篇)
- 商業(yè)伙伴與合作伙伴管理制度
評(píng)論
0/150
提交評(píng)論