1 / 30

Chapter 10 - Structures & Classes

Chapter 10 - Structures & Classes. What is a Programming Language? Demonstrate how to combine values of different variable types in one variable Introduce how to define a Structure Explain how to use Structures Explain how to use Arrays of Structures Introduce concept of encapsulation

milica
Télécharger la présentation

Chapter 10 - Structures & Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10 - Structures & Classes • What is a Programming Language? • Demonstrate how to combine values of different variable types in one variable • Introduce how to define a Structure • Explain how to use Structures • Explain how to use Arrays of Structures • Introduce concept of encapsulation • Introduce C++ Classes Introduce new terms associated with classes. The C++ Coach - Essentials for Introductory Programming - 2000

  2. Chapter 10 - Structures & Classes 10.1 Defining a Structure The following template is used for creating a structure in C++: struct StructureName { VariableType1 VariableName1; VariableType2 VariableName2; VariableType3 VariableName3; }; The keyword struct must start each structure definition. The StructureName is the name that you will refer to the structure by within your program. Let's look at an example of how we would define a structure for a program. struct StudentRecord { char Name[20]; int ID; float GPA; }; A graphical representation of the structure we just created would look as follows: The C++ Coach - Essentials for Introductory Programming - 2000

  3. Chapter 10 - Structures & Classes 10.1 Defining a Structure However, this is not how a structure really appears in the computer. In a computer, the information would be stored in a single dimension. This is shown in the following figure: Drill 10-1 Declare a structure called DrillStructure1 that contains two integers called Integer1 and Integer2 as well as two floating point numbers called Float1 and Float2. The structure definition for the drill is as follows: struct DrillStructure1 { int Integer1; int Integer2; float Float1; float Float2; }; The C++ Coach - Essentials for Introductory Programming - 2000

  4. Chapter 10 - Structures & Classes 10.1 Defining a Structure Drill 10-2 Declare a structure called DrillStructure2 that contains an array of ten integers called Integers, an array of ten floating point numbers called Floats, and an array of ten characters called Characters. The structure definition for the drill is as follows: struct DrillStructure2 { int Integers[10]; float Floats[10]; char Characters[10]; }; Declaring Variables from Structures To create a structure, we simple type the structure name, a space, and the variable name we want to refer to the structure by within the program. StructureName VariableName; Therefore to create a variable called GradesJohnC of a structure called StudentRecord, we would use the following code: StudentRecord GradesJohnC; The C++ Coach - Essentials for Introductory Programming - 2000

  5. Chapter 10 - Structures & Classes 10.1 Defining a Structure The following template shows a field being accessed from a structure with the result being sent to a cout statement: cout<<VariableName.AttributeName; If we wanted to access a single field from the previously defined GradesJohnC variable, we could do so with the following code in which GradesJohnC has its GPA field set to 4.0: GradesJohnC.GPA=4.0; We now know enough to be able to use structures within a program. So let's try. What if we wished to create a catalog of DVDs that we own? The following will define our Movie structure as follows: struct Movie { char Name[100]; int Year; int Time; float Stars; }; The C++ Coach - Essentials for Introductory Programming - 2000

  6. Chapter 10 - Structures & Classes 10.1 Defining a Structure If we wish to declare a variable of type Movie we simply use the newly defined type just like any other predefined type like int, float or char. Movie DVD1; Next we will want to assign values to this structure. We assign values to structures in a similar fashion as we do with regular variables. DVD1.Year = 1974; DVD1.Yime = 91; DVD1.Stars = 5; In order to initialize the Title, we can not use an equal sign. Instead, we will call the StrCpy function as shown below. StrCpy(DVD1.Title, "Monty Python and the Holy Grail"); Just as with arrays, if we wish to initialize the values of a structure at the time of declaration, we can do it by enclosing the values to be assigned in curly braces and separate the individual values by commas. The following code demonstrates assigning DVD1 the same values, but at the time of declaration: Movie DVD1 = {"Monty Python and the Holy Grail", 1974, 91, 5}; The C++ Coach - Essentials for Introductory Programming - 2000

  7. Chapter 10 - Structures & Classes 10.1 Defining a Structure Now that we have declared a structure and assigned it a value, let's use it as we would any other variable. If we wanted to print the movie information contained in the structure, we would use the following code: cout<<"The Movie "<<DVD1.Name<<" was made in "<<DVD1.Year <<" ,runs "<<DVD1.Time <<" minutes in length and received "<<DVD1.Stars<<" stars"<<endl; The output will be: The Movie Monty Python and the Holy Grail was made in 1975,runs 91 minutes in length and received 5 stars Just as we assign values using different operators with regular variables, we can do so with structures. See the following code that shows three ways of adding one to the year in the structure DVD1: DVD1.Year = DVD1.Year + 1; DVD1.Year += 1; DVD1.Year++; The C++ Coach - Essentials for Introductory Programming - 2000

  8. Chapter 10 - Structures & Classes 10.1 Defining a Structure //Movie Example //Include Files #include <stdlib.h> #include <iostream.h> #define MaxStringSize 100 //Structure Definitions struct Movie { char name[MaxStringSize]; int Year; int Time; float Stars; }; //Prototypes void Initialize(Movie & DVD); void Display(Movie DVD); void CompareMovies(Movie DVD1, Movie DVD2); The C++ Coach - Essentials for Introductory Programming - 2000

  9. Chapter 10 - Structures & Classes 10.1 Defining a Structure //Main Routine void main() { Movie DVD1, DVD2; Initialize(DVD1); Initialize(DVD2); CompareMovies(DVD1, DVD2); } //Functions //Initialize Movie Function void Initialize(Movie & DVD1) { cout<<endl<<"Enter the title of the movie"<<endl; cin>>DVD1.Name; cout<<endl<<"Enter the year the movie was made"<<endl; cin>>DVD1.Year; cout<<endl<<"Enter the running time of the movie"<<endl; cin>>DVD1.Time; cout<<endl<<"Enter the number of stars of the movie"<<endl; cin>>DVD1.Stars; } The C++ Coach - Essentials for Introductory Programming - 2000

  10. Chapter 10 - Structures & Classes 10.1 Defining a Structure //Display Movie Function void Display(Movie DVD1) { cout<<"The Movie "<<DVD1.Name <<" was made in "<<DVD1.Year<<" ,runs "<<DVD1.Time <<" minutes in length and received "<<DVD1.Stars<<" stars"<<endl; } //Compare Movie Function void CompareMovies(Movie DVD1, Movie DVD2) { if (DVD1.Stars > DVD2.Stars) { Display(DVD1); cout<<" and is the better Movie" <<endl; } else if (DVD2.Stars > DVD1.Stars) { Display(DVD2); cout<<" and is the better Movie" <<endl; } else { Display(DVD1); Display(DVD2); cout<< "are both rated the same"<<endl; } } The C++ Coach - Essentials for Introductory Programming - 2000

  11. Chapter 10 - Structures & Classes 10.1 Defining a Structure Drill 10-3 Write the code required to create a variable called StructureVariable of the structure declared in Drill 10-1. The code required to create a variable called StructureVariable is as follows: DrillStructure1 StructureVariable; The C++ Coach - Essentials for Introductory Programming - 2000

  12. Chapter 10 - Structures & Classes 10.1 Defining a Structure Drill 10-4 Write the code required to set the attribute Integer1 to 100 for the variable created in Drill 10-3. The code required to set the attribute Integer1 to 100 is as follows: StructureVariable.Integer1 = 100; The C++ Coach - Essentials for Introductory Programming - 2000

  13. Chapter 10 - Structures & Classes 10.1 Defining a Structure Drill 10-5 Write the code required to create a variable called StructureVariable of the structure declared in Drill 10-2. The code required to create a variable called StructureVariable is as follows: DrillStructure2 StructureVariable; The C++ Coach - Essentials for Introductory Programming - 2000

  14. Chapter 10 - Structures & Classes 10.1 Defining a Structure Drill 10-6 Write the code require to initialize the first 5 integers of the attribute Integers in the variable declared in Drill 10-5 to 1, 2, 3, 4, & 5 respectively. The code required to initialize the first 5 integers for this drill is as follows: StructureVariable.Integers[0]=1; StructureVariable.Integers[1]=2; StructureVariable.Integers[2]=3; StructureVariable.Integers[3]=4; StructureVariable.Integers[4]=5; The C++ Coach - Essentials for Introductory Programming - 2000

  15. Chapter 10 - Structures & Classes 10.2 Arrays of Structures At the beginning of this chapter we stated that arrays could not contain more than one type of variable, however with arrays of structures we can accomplish this. Movie Collection[10]; //declares an array of ten movies. //will assign the first title in the collection array to Fletch. strcpy(Collection[0].Name, "Fletch"); You can initialize the array of structures at the time of declaration similarly to the way you did with a single structure or simple array. Movie Collection[]={ {"Monty Python and the Holy Grail", 1975, 91, 5}, {"Fletch", 1985, 98, 5}, {"Trading Places", 1983, 118,5}}; The C++ Coach - Essentials for Introductory Programming - 2000

  16. Chapter 10 - Structures & Classes 10.2 Arrays of Structures Drill 10-7 Declare an array called ArrayOfStuctures of five DrillStructure1's that we defined in Drill 10-1. To declare an array of five DrillStructure1's we defined in Drill 10-1, we need the following code: DrillStructure1 ArrayOfStructures[5]; The C++ Coach - Essentials for Introductory Programming - 2000

  17. Chapter 10 - Structures & Classes 10.2 Arrays of Structures Drill 10-8 Write the code required to initialize the first array element of the array declared in Drill 10-7 to 1, 2, 3.5, and 4.5 respectively. To initialize the first array element of the array declared in Drill 10-7 to 1, 2, 3.5, and 4.5 respectively, we need the following code: ArrayOfStructures[0].Integer1=1; ArrayOfStructures[0].Integer2=2; ArrayOfStructures[0].Float1=3.5; ArrayOfStructures[0].Float2=4.5; The C++ Coach - Essentials for Introductory Programming - 2000

  18. Chapter 10 - Structures & Classes 10.2 Arrays of Structures Drill 10-9 To declare an array of five DrillStructure1's we defined in Drill 10-1, we need the following code: DrillStructure2 ArrayOfStructures[5]; The C++ Coach - Essentials for Introductory Programming - 2000

  19. Chapter 10 - Structures & Classes 10.2 Arrays of Structures Drill 10-10 Write the code required to initialize the first five integers of the first array element of the array declared in Drill 10-9 to 1, 2, 3, 4 & 5 respectively. To declare an array of five DrillStructure1's we defined in Drill 10-1, we need the following code: DrillStructure2 ArrayOfStructures[5]; The C++ Coach - Essentials for Introductory Programming - 2000

  20. Chapter 10 - Structures & Classes 10.3 Concept of a Class The introduction of classes is the beginning of what many people call the core of C++. By using classes we can improve upon the concepts of structures, making them more versatile. With classes, we can control the way that a variable of a class is initialized. We can also ensure that the data stored in a variable is "correct". Imagine if we had an integer variable that was supposed to represent the minute portion of a time. We would not want to the value to be beyond the range of 0-59. An integer could be between the range -32,768 to 32,767. By providing control over these issues, classes provide a "user-interface" over our data. Unfortunately, learning classes opens a programmer up to countless options that lead to a great deal of confusion. For our purposes, we will learn a subset of the options classes offer and focus on the concept that teaches us how to encapsulate a structure and the operations that are performed on it under one construct. In addition, we will learn the basic concepts of reusing code via inheritance. Encapsulationenables the programmer designing the class to dictate what types of operations are permissible upon a class without permitting other programmers access to the inner workings of the class. In essence the class designer allows other programmers to have the complexity of a class hidden and ensure that other programmers can only use the class in ways intended by the programmer designing the class. The C++ Coach - Essentials for Introductory Programming - 2000

  21. Chapter 10 - Structures & Classes 10.4 Defining a Class A basic class definition follows the following template: class ClassName { public: //Public methods and attributes private: // Private methods and attributes }; A method is a function that is defined inside a class. A method is defined as follows: ReturnType ClassName :: MethodName(Parameter List) { Body of method; } If an object is created of a specific class, its method can be called by stating the object name, following it with a dot operator, following it with the method name, and following it with a parameter list enclosed within a set of parentheses. The parameter list may be empty, however the set of parentheses is still required. ClassName ObjectName; ObjectName.MethodName(Parameter List); The C++ Coach - Essentials for Introductory Programming - 2000

  22. Chapter 10 - Structures & Classes 10.4 Defining a Class Here is the class definition for Counter: class Counter { public: Counter(); Counter(int IValue); void Increment(); void Decrement(); void Display(); int Value(); void Reset(); private: int Count; int InitialValue; }; The first two methods of the class Counter are special, they are called constructors. Counter :: Counter() { Count = 0; InitialValue = 0; } Counter :: Counter(int Ivalue) { Count = IValue; InitialValue = IValue; } The C++ Coach - Essentials for Introductory Programming - 2000

  23. Chapter 10 - Structures & Classes 10.4 Defining a Class The next method is Increment. It simply increments the attribute Count by 1 and returns nothing. void Counter :: Increment() { Count++; } The Decrement method is similar to the Increment method. The only difference is that instead of adding one, we subtract one from Count. void Counter :: Decrement() { Count--; } The Display method takes the private attribute Count and display it: void Counter :: Display() { cout<<Count<<endl; } The C++ Coach - Essentials for Introductory Programming - 2000

  24. Chapter 10 - Structures & Classes 10.4 Defining a Class The Reset methods takes the orginial value the Counter was set to and resets it to that value: void Counter :: Reset() { Count = InitialValue; } The final method Value returns the private attibute Count to the caller of the method: int Counter :: Value() { return Count; } The following is an example of a program using our Counter class. It initializes a counter to 10 and then decrements it until it reaches 0. The code follows: void main() { Counter Count(10); do { Count.Decrement(); Count.Display(); } while(Count.Value()>0); } The C++ Coach - Essentials for Introductory Programming - 2000

  25. Chapter 10 - Structures & Classes • 10.5 Case Study • Problem Description • For this case study, let's create another class that would simulate an alarm clock The alarm clock class should: • Store a time in hours, minutes, and seconds. • Keep track if we are in the AM or PM. • Initializing a clock to a specific time. • Increment the clock to the next second. • Set the alarm. • Display the current time. The C++ Coach - Essentials for Introductory Programming - 2000

  26. Chapter 10 - Structures & Classes 10.5 Case Study Solution class AlarmClock { public: AlarmClock(); AlarmClock(int h, int m, int s, char A_P); void Display(); void SetAlarmTime(int h, int m, int s, char A_P); void Increment(); private: //Time Attributes int hours; int minutes; int seconds; char AM_PM; //Alarm attributes int Ahours; int Amintues; int Aseconds; char A_AM_PM; bool On; //private methods CheckAlarm(); }; The C++ Coach - Essentials for Introductory Programming - 2000

  27. Chapter 10 - Structures & Classes 10.5 Case Study Solution AlarmClock :: AlarmClock() { hours=12; minutes=0; seconds=0; AM_PM = 'A'; On=false; } AlarmClock :: AlarmClock(int h, int m, int s, int A_P) { hours=h; minutes=m; seconds=s; AM_PM = A_P; On=false; } void AlarmClock :: Display() { cout<<hours<<":"<<minutes<<":"<<seconds<<" "; if (AM_PM=='A') cout<<"AM"<<endl; else cout<<"PM"<<endl; } The C++ Coach - Essentials for Introductory Programming - 2000

  28. Chapter 10 - Structures & Classes 10.5 Case Study Solution void AlarmClock :: Increment() { seconds++; if (seconds==60) { seconds=0; minutes++; if (minutes==60) { minutes=0; hours++; if (hours==12) if (AM_PM=='A') AM_PM='P'; else AM_PM='A'; else if (hours==13) hours=1; } } CheckAlarm(); } The C++ Coach - Essentials for Introductory Programming - 2000

  29. Chapter 10 - Structures & Classes 10.5 Case Study Solution void AlarmClock :: SetAlarmTime(int h, int m, int s, char A_P) { Ahours=h; Aminutes=m; Aseconds=s; A_AM_PM = A_P; On=true; } void AlarmClock :: CheckAlarm() { if (On && (Ahours==hours) && (Aminutes==minutes) && (Aseconds == seconds) && (A_AM_PM == AM_PM)) cout<<"WAKE UP, ITS TIME TO GO TO SCHOOL!\n"; } The C++ Coach - Essentials for Introductory Programming - 2000

  30. Chapter 10 - Structures & Classes 10.5 Case Study Solution #include <stdlib.h> #include <iostream.h> //Class definition for AlarmClock goes here void main() { AlarmClock JeffClock; AlarmClock SchoolClock(8,10,0,'A'); JeffClock.Display(); SchoolClock.Display(); SchoolClock.SetAlarm(8,20,0,'A'); for(int i=0; i<5000; i++) SchoolClock.Increment(); SchoolClock.Display(); } The C++ Coach - Essentials for Introductory Programming - 2000

More Related