版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 开题报告:疫情常态下ISO+AI驱动的线上教学质量保障与提升体系研究
- 临时施工用电专项方案2
- 开题报告:信息科技课程大概念谱系构建原理、方法及教学研究
- 开题报告:新时代民办教育发展战略和治理创新研究
- 《膜分离技术》课件
- 《CAD基本练习》课件
- 2024年度企业业务外包个人承包合同
- 2024年区域独家销售代表协议版
- 《财产条款培训》课件
- 2024年度互联网金融平台运营与监管合同
- 中心传动刮泥机现场施工方案
- 论农村科技创新型人才存在的问题及对策
- 儿童诗儿童诗的欣赏和创作(课件)
- 中国科学技术大学抬头信纸(word版)
- 人力资源管理工作思路(共3页)
- 气管切开(一次性气切导管)护理评分标准
- 保安工作日志表
- 姜太公钓鱼的历史故事
- 数控车床实训图纸国际象棋图纸全套
- 自动控制原理部分重点整理版
- 归去来兮辞PPT课件
评论
0/150
提交评论