用C++解決問(wèn)題第十版-第10章定義班級(jí)_第1頁(yè)
用C++解決問(wèn)題第十版-第10章定義班級(jí)_第2頁(yè)
用C++解決問(wèn)題第十版-第10章定義班級(jí)_第3頁(yè)
用C++解決問(wèn)題第十版-第10章定義班級(jí)_第4頁(yè)
用C++解決問(wèn)題第十版-第10章定義班級(jí)_第5頁(yè)
已閱讀5頁(yè),還剩92頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

1、Chapter 10Defining ClassesOverview10.1 Structures 10.2 Classes10.3 Abstract Data Types10.4 Introduction to InheritanceSlide 10- 310.1StructuresWhat Is a Class?A class is a data type whose variables are objectsSome pre-defined data types you have used are intcharA pre-defined class you have used isif

2、streamYou can define your own classes as wellSlide 10- 5Class DefinitionsA class definition includesA description of the kinds of values the variable can holdA description of the member functionsWe will start by defining structures as a firststep toward defining classesSlide 10- 6StructuresA structu

3、re can be viewed as an objectContains no member functions (The structures used here have no member functions)Contains multiple values of possibly different typesThe multiple values are logically related as a single itemExample: A bank Certificate of Deposit (CD) has the following values: a balance a

4、n interest ratea term (months to maturity)Slide 10- 7The CD DefinitionThe Certificate of Deposit structure can bedefined asstruct CDAccount double balance;double interestRate; int term; /months to maturity;Keyword struct begins a structure definitionCDAccount is the structure tag or the structures t

5、ype Member names are identifiers declared in the bracesSlide 10- 8Remember this semicolon!Using the StructureStructure definition is generally placed outsideany function definitionThis makes the structure type available to all code that follows the structure definitionTo declare two variables of typ

6、e CDAccount: CDAccount myAccount, yourAccount;myAccount and yourAccount contain distinct member variables balance, interestRate, and termSlide 10- 9The Structure ValueThe Structure ValueConsists of the values of the member variablesThe value of an object of type CDAccountConsists of the values of th

7、e member variables balance interestRatetermSlide 10- 10Specifying Member VariablesMember variables are specific to the structure variable in which they are declaredSyntax to specify a member variable: Structure_Variable_Name . Member_Variable_NameGiven the declaration: CDAccount myAccount, yourAccou

8、nt;Use the dot operator to specify a member variablemyAccount.balance myAerestRatemyAccount.termSlide 10- 11Using Member VariablesMember variables can be used just as any othervariable of the same typemyAccount.balance = 1000;yourAccount.balance = 2500;Notice that myAccount.balance and you

9、rAccount.balance are different variables!myAccount.balance = myAccount.balance + interest;Slide 10- 12Display 10.1 (1)Display 10.1 (2)Display 10.2 Duplicate NamesMember variable names duplicated between structure types are not a problem. superGrow.quantity and apples.quantity are different variables

10、 stored in different locationsSlide 10- 13struct FertilizerStock double quantity; double nitrogenContent;FertilizerStock superGrow;struct CropYield int quantity; double size;CropYield apples;Structures as ArgumentsStructures can be arguments in function callsThe formal parameter can be call-by-value

11、The formal parameter can be call-by-referenceExample:void getData(CDAccount& theAccount);Uses the structure type CDAccount we saw earlier as the type for a call-by-reference parameterSlide 10- 14Structures as Return TypesStructures can be the type of a value returned bya functionExample:CDAccount sh

12、rinkWrap(double theBalance, double theRate, int theTerm) CDAccount temp; temp.balance = theBalance; erestRate = theRate; temp.term = theTerm; return temp;Slide 10- 15Using Function shrinkWrapshrinkWrap builds a complete structure valuein temp, which is returned by the functionWe can use shri

13、nkWrap to give a variable of type CDAccount a value in this way: CDAccount newAccount; newAccount = shrinkWrap(1000.00, 5.1, 11);Slide 10- 16Assignment and StructuresThe assignment operator can be used to assignvalues to structure typesUsing the CDAccount structure again:CDAccount myAccount, yourAcc

14、ount;myAccount.balance = 1000.00;myAerestRate = 5.1;myAccount.term = 12;yourAccount = myAccount;Assigns all member variables in yourAccount the corresponding values in myAccountSlide 10- 17Hierarchical StructuresStructures can contain member variables that are also structuresstruct PersonI

15、nfo contains a Date structureSlide 10- 18struct Date int month; int day; int year;struct PersonInfo double height; int weight; Date birthday;Using PersonInfoA variable of type PersonInfo is declared by PersonInfo person1;To display the birth year of person1, first access the birthday member of perso

16、n1 cout person1.birthdayBut we want the year, so we now specify the year member of the birthday member cout person1.birthday.year;Slide 10- 19Initializing ClassesA structure can be initialized when declaredExample: struct Date int month; int day; int year;Can be initialized in this way Date dueDate

17、= 12, 31, 2004;Slide 10- 20Section 10.1 ConclusionCan youWrite a definition for a structure type for records consisting of a persons wage rate, accrued vacation (in whole days), and status (hourly or salaried). Represent the status as one of the two character values H and S. Call the type EmployeeRe

18、cord.Slide 10- 2110.2ClassesClassesA class is a data type whose variables are objectsThe definition of a class includesDescription of the kinds of values of the membervariablesDescription of the member functionsA class description is somewhat like a structure definition plus the member variablesSlid

19、e 10- 23A Class ExampleTo create a new type named DayOfYear as a class definitionDecide on the values to representThis examples values are dates such as July 4using an integer for the number of the monthMember variable month is an int (Jan = 1, Feb = 2, etc.)Member variable day is an intDecide on th

20、e member functions neededWe use just one member function named outputSlide 10- 24Class DayOfYear Definitionclass DayOfYear public: void output( ); int month; int day;Slide 10- 25Member Function DeclarationDefining a Member FunctionMember functions are declared in the classdeclaration Member function

21、 definitions identify the classin which the function is a membervoid DayOfYear:output() cout “month = “ month “, day = “ day endl; Slide 10- 26Member Function DefinitionMember function definition syntax:Returned_Type Class_Name:Function_Name(Parameter_List) Function Body StatementsExample: void DayO

22、fYear:output( ) cout “month = “ month “, day = “ day today.month will no longer work becausewe now have three character variables to readif(today.month = birthday.month) will no longerwork to compare monthsThe member function “output” no longer worksSlide 10- 32Ideal Class DefinitionsChanging the im

23、plementation of DayOfYear requires changes to the program that uses DayOfYearAn ideal class definition of DayOfYear could be changed without requiring changes tothe program that uses DayOfYearSlide 10- 33Fixing DayOfYear To fix DayOfYearWe need to add member functions to use when changing or accessi

24、ng the member variablesIf the program never directly references the member variables, changing how the variables are stored will notrequire changing the programWe need to be sure that the program does not ever directly reference the member variablesSlide 10- 34Public Or Private?C+ helps us restrict

25、the program from directly referencing member variablesprivate members of a class can only be referenced within the definitions of member functionsIf the program tries to access a private member, thecompiler gives an error messagePrivate members can be variables or functionsSlide 10- 35Private Variab

26、lesPrivate variables cannot be accessed directly by the programChanging their values requires the use of publicmember functions of the classTo set the private month and day variables in a new DayOfYear class use a member function such as void DayOfYear:set(int new_month, int new_day) month = new_mon

27、th; day = new_day; Slide 10- 36Public or Private MembersThe keyword private identifies the members of a class that can be accessed only by member functions of the classMembers that follow the keyword private are private members of the classThe keyword public identifies the members of a class that ca

28、n be accessed from outside the classMembers that follow the keyword public are public members of the classSlide 10- 37A New DayOfYearThe new DayOfYear class demonstrated in Display 10.4Uses all private member variablesUses member functions to do all manipulation of the private member variablesMember

29、 variables and member function definitions can bechanged without changes to theprogram that uses DayOfYear Slide 10- 38Display 10.4 (1)Display 10.4 (2)Using Private VariablesIt is normal to make all member variables privatePrivate variables require member functions to perform all changing and retrie

30、ving of valuesAccessor functions allow you to obtain the values of member variablesExample: getDay in class DayOfYearMutator functions allow you to change the valuesof member variablesExample: set in class DayOfYear Slide 10- 39General Class DefinitionsThe syntax for a class definition isclass Class

31、_Name public: Member_Specification_1 Member_Specification_2Member_Specification_3private:Member_Specification_n+1Member_Specification_n+2;Slide 10- 40Declaring an ObjectOnce a class is defined, an object of the class isdeclared just as variables of any other typeExample: To create two objects of typ

32、e Bicycle: class Bicycle / class definition lines; Bicycle myBike, yourBike; Slide 10- 41The Assignment OperatorObjects and structures can be assigned valueswith the assignment operator (=)Example: DayOfYear dueDate, tomorrow; tomorrow.set(11, 19); dueDate = tomorrow;Slide 10- 42Program Example:Bank

33、Account ClassThis bank account class allows Withdrawal of money at any timeAll operations normally expected of a bank account (implemented with member functions)Storing an account balanceStoring the accounts interest rateSlide 10- 43Display 10.5 ( 1)Display 10.5 ( 2)Display 10.5 ( 3)Display 10.5 ( 4

34、)Calling Public Members Recall that if calling a member function from the main function of a program, you must includethe the object name: account1.update( );Slide 10- 44Calling Private MembersWhen a member function calls a private member function, an object name is not usedfraction (double percent)

35、; is a private member of the BankAccount classfraction is called by member function update void BankAccount:update( ) balance = balance + fraction(interestRate)* balance; Slide 10- 45ConstructorsA constructor can be used to initialize membervariables when an object is declaredA constructor is a memb

36、er function that is usually publicA constructor is automatically called when an objectof the class is declaredA constructors name must be the name of the classA constructor cannot return a valueNo return type, not even void, is used in declaring or defining a constructorSlide 10- 46Constructor Decla

37、rationA constructor for the BankAccount class could be declared as: class BankAccount public: BankAccount(int dollars, int cents, double rate); /initializes the balance to $dollars.cents /initializes the interest rate to rate percent /The rest of the BankAccount definition ;Slide 10- 47Constructor D

38、efinitionThe constructor for the BankAccount class could be defined asBankAccount:BankAccount(int dollars, int cents, double rate) if (dollars 0) | (cents 0) | ( rate 0 ) cout “Illegal values for money or raten”; exit(1); balance = dollars + 0.01 * cents; interestRate = rate;Note that the class name

39、 and function name are the sameSlide 10- 48Calling A Constructor (1)A constructor is not called like a normal memberfunction: BankAccount account1; account1.BankAccount(10, 50, 2.0);Slide 10- 49Calling A Constructor (2)A constructor is called in the object declaration BankAccount account1(10, 50, 2.

40、0);Creates a BankAccount object and calls the constructor to initialize the member variablesSlide 10- 50Overloading ConstructorsConstructors can be overloaded by definingconstructors with different parameter listsOther possible constructors for the BankAccountclass might beBankAccount (double balanc

41、e, double interestRate);BankAccount (double balance); BankAccount (double interestRate); BankAccount ( );Slide 10- 51The Default ConstructorA default constructor uses no parametersA default constructor for the BankAccount classcould be declared in this wayclass BankAccount public: BankAccount( ); /

42、initializes balance to $0.00 / initializes rate to 0.0% / The rest of the class definition;Slide 10- 52Default Constructor DefinitionThe default constructor for the BankAccountclass could be defined asBankAccount:BankAccount( ) balance = 0; rate = 0.0; It is a good idea to always include a default c

43、onstructoreven if you do not want to initialize variablesSlide 10- 53Calling the Default ConstructorThe default constructor is called during declaration of an objectAn argument list is not usedBankAccount account1; / uses the default BankAccount constructorBankAccount account1( ); / Is not legalSlid

44、e 10- 54Display 10.6 (1)Display 10.6 (2)Display 10.6 (3)Initialization SectionsAn initialization section in a function definitionprovides an alternative way to initialize member variablesBankAccount:BankAccount( ): balance(0), interestRate(0.0); / No code needed in this exampleThe values in parenthe

45、sis are the initial values for the member variables listedSlide 10- 55Parameters and InitializationMember functions with parameters can use initialization sectionsBankAccount:BankAccount(int dollars, int cents, double rate) : balance (dollars + 0.01 * cents), interestRate(rate) if ( dollars 0) | (ce

46、nts 0) | (rate 0) cout “Illegal values for money or raten”; exit(1); Notice that the parameters can be arguments in the initializationSlide 10- 56Member InitializersC+11 supports a feature called member initializationSimply set member variables in the classEx: class Coordinate private:int x=1;int y=

47、2;. ; Creating a Coordinate object will initialize its x variable to 1 and y to 2 (assuming a constructor isnt called that sets the values to something else)Slide 10- 57Constructor DelegationC+11 also supports constructor delegation. This lets you have a constructor invoke another constructor in the

48、 initialization section.For example, make the default constructor call a second constructor that sets X to 99 and Y to 99:Coordinate:Coordinate() : Coordinate(99,99) Slide 10- 58Section 10.2 ConclusionCan youDescribe the difference between a class and a structure?Explain why member variables are usu

49、ally private?Describe the purpose of a constructor?Use an initialization section in a function definition?Slide 10- 5910.3Abstract Data TypesAbstract Data TypesA data type consists of a collection of valuestogether with a set of basic operations defined on the valuesA data type is an Abstract Data T

50、ype (ADT)if programmers using the type do not haveaccess to the details of how the values andoperations are implementedSlide 10- 61Classes To Produce ADTsTo define a class so it is an ADTSeparate the specification of how the type is usedby a programmer from the details of how the typeis implementedM

51、ake all member variables private membersBasic operations a programmer needs should be public member functionsFully specify how to use each public functionHelper functions should be private members Slide 10- 62ADT InterfaceThe ADT interface tells how to use the ADT ina programThe interface consists o

52、f The public member functionsThe comments that explain how to use the functionsThe interface should be all that is needed to know how to use the ADT in a programSlide 10- 63ADT ImplementationThe ADT implementation tells how the interface is realized in C+The implementation consists of The private me

53、mbers of the classThe definitions of public and private member functionsThe implementation is needed to run a programThe implementation is not needed to write the main part of a program or any non-member functionsSlide 10- 64ADT BenefitsChanging an ADT implementation does requirechanging a program t

54、hat uses the ADTADTs make it easier to divide work among different programmersOne or more can write the ADTOne or more can write code that uses the ADTWriting and using ADTs breaks the larger programming task into smaller tasksSlide 10- 65Program ExampleThe BankAccount ADTIn this version of the Bank

55、Account ADTData is stored as three member variablesThe dollars part of the account balanceThe cents part of the account balanceThe interest rateThis version stores the interest rate as a fractionThe public portion of the class definition remainsunchanged from the version of Display 10.6 Slide 10- 66

56、Display 10.7 (1)Display 10.7 (2)Display 10.7 (3)Interface PreservationTo preserve the interface of an ADT so that programs using it do not need to be changedPublic member declarations cannot be changedPublic member definitions can be changedPrivate member functions can be added, deleted, or changedS

57、lide 10- 67Information HidingInformation hiding was refered to earlier as writing functions so they can be used like black boxesADTs implement information hiding becauseThe interface is all that is needed to use the ADTImplementation details of the ADT are not needed to know how to use the ADTImplem

58、entation details of the data values are notneeded to know how to use the ADTSlide 10- 68Section 10.3 ConclusionCan youDescribe an ADT?Describe how to implement an ADT in C+?Define the interface of an ADT?Define the implementation of an ADT?Slide 10- 6910.4Introduction to InheritanceInheritanceInheri

59、tance refers to derived classesDerived classes are obtained from another class by adding featuresA derived class inherits the member functions and variables from its parent class without having to re-write themExampleIn Chapter 6 we saw that the class of input-file streams is derived from the class of all input streams by adding member functions such as open and closecin belongs to the class of all input stream

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(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ì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論