Download presentation
Presentation is loading. Please wait.
Published byGiles Crawford Modified over 9 years ago
1
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 10 Structured Data
2
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 2 Topics 10.1 Abstract Data Types 10.2 Combining Data into Structures 10.3 Accessing Structure Members 10.4 Initializing a Structure 10.5 Arrays of Structures 10.6 Nested Structures
3
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 3 Topics 10.7 Structures as Function Arguments 10.8 Returning a Structure from a Function 10.9 Pointers to Structures 10.10 When to Use., ->, * 10.11 Unions 10.12 Enumerations
4
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 4 10.1 Abstract Data Types New Aggregate Data Types / New Abstract Data Types Structures ( create new aggregate data types ) –allow you to create new data types composed of multiple primitive data types. –You define the type name ( tag ) and the names of the members. Classes (create new ADT's ) –allow you to create new abstract data types. –You define the attributes ( data elements ) –You define the behaviors ( operations which may be performed on the attributes ) –attributes and behaviors are encapsulated in a class definition.
5
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 5 Abstraction and Data Types Abstraction: –a definition that captures general characteristics without details –Example: An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: – defines the values that can be stored in a variable and the operations that can be performed on it
6
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 6 10.2 Focus on Software Engineering: Combining Data into Structures : C / C++ allows you to group several variables together into a single item known as a structure. The components (individual elements) of the structure are called members. Access to structure members is public. Structures are similar to classes ( data, but no operations…).
7
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 7 10.2 Combining Data into Structures Structure: –C++ construct that allows multiple variables to be grouped together Format: struct { type1 field1; type2 field2;... };
8
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 8 Review - Primitive Data Types C++ has several primitive data types Table 10-1
9
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 9 Table 10-2 Independent Variables
10
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 10 Example Structure Declaration struct PayRoll { int EmpNumber; char Name[25]; double Hours; double PayRate; double GrossPay; }; // The semicolon is required. PayRoll is the "tag." Use it as a new data type for structure variables you wish to create. This structure declaration declares a new type. It does not actually allocate any memory or declare any variables of the type. EmpNumber, Name, Hours, PayRate and GrossPay are called structure members.
11
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 11 Figure 10-1 empNumber name hours payRate grossPay PayRoll Structure Variable Tag ( type ) Members
12
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 12 Figure 10-2 Structure variables of type Payroll PayRoll deptHead, foreman, associate; empNumber name hours payRate grossPay deptHead empNumber name hours payRate grossPay foreman empNumber name hours payRate grossPay associate
13
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 13 Example struct Declaration struct Student { int studentID; string name; short yearInSchool; double gpa; }; structure tag structure members
14
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 14 struct Declaration Notes Must have ; after closing } struct names commonly begin with an uppercase letter Multiple fields of same type can be defined using a comma-separated list: string name, address;
15
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 15 Defining Variables struct declaration does not allocate memory or create variables To define variables, use structure tag as type name: Student stu1; studentID name yearInSchool gpa stu1
16
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 16 10.3 Accessing Structure Members Use the dot (.) operator to refer to members of struct variables: cin >> stu1.studentID; getline(cin, stu1.name); stu1.gpa = 3.75; The dot operator is also called the member access operator
17
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 17 Displaying a struct Variable To display the contents of a struct variable, you must display each field separately, using the dot operator: cout << stu1; // won’t work cout << stu1.studentID << endl; cout << stu1.name << endl; cout << stu1.yearInSchool << " " << stu1.gpa << endl;
18
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 18 Comparing struct Variables Cannot compare struct variables directly: if (stu1 == stu2) // won’t work Instead, must compare on a member basis: if (stu1.studentID == stu2.studentID)
19
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 19 10.4 Initializing a Structure Variable A struct variable can be initialized when defined: Student stu2 = {11465, "Joan", 2, 3.75}; It can also be initialized member-by- member after definition: stu2.name = "Joan"; stu2.gpa = 3.75;
20
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 20 More on Initializing a Structure May initialize only some members: Student stu3 = {14579}; Cannot skip over members: Student stu4 = {1234, "John",,2.83}; // illegal You cannot initialize the members in the structure declaration, since this does not allocate memory.
21
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 21 10.5 Arrays of Structures Structures can be defined in arrays Structures can be used in place of parallel arrays Student stuList[20]; Individual structures accessible using subscript notation Fields within structures accessible using dot notation: cout << stuList[5].studentID;
22
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 22 10.6 Nested Structures A structure can contain another structure as a member: struct PersonInfo { string name, address, city; }; struct Student {int studentID; PersonInfo pData; //nested structure short yearInSchool; float gpa; };
23
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 23 Members of Nested Structures Use the dot operator multiple times to refer to fields of nested structures: In the example that follows: –pData ( a PersonInfo structure ) has three members name, address and city Student stu5; stu5.pData.name = "Joanne"; stu5.pData.city = "Tulsa";
24
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 24 10.7 Structures as Function Arguments You may pass members of struct variables to functions: computeGPA(stu1.gpa); You may pass entire struct variables to functions: showData(stu5); You can use a reference parameter (reference or pointer) if a function needs to modify the members of a structure variable void changeStudentData(Student &); //use a reference void changeStudentData(Student *); //use a pointer
25
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 25 Structures as Function Arguments - Notes Passing a structure by value can slow down a program, waste space Passing a structure by reference will speed up the program, but function may change data in structure Using a const reference parameter allows read-only access to the reference parameter, does not waste space or slow execution. void printStudentData(const Student &); void printStudentData(const Student *);
26
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 26 10.8 Returning a Structure from a Function A function can return a struct : Student getStudentData(); // prototype stu1 = getStudentData(); // call The function must define a local structure –for use with return statement
27
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 27 Returning a Structure from a Function Example Student getStuData() { Student tmpStu; cin >> tmpStu.studentID; //get data for string members… getline(cin, tmpStu.pData.name); getline(cin, tmpStu.pData.address); getline(cin, tmpStu.pData.city); cin >> tmpStu.yearInSchool; cin >> tmpStu.gpa; return tmpStu; }
28
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 28 10.9 Pointers to Structures A structure variable has an address Pointers to structures are variables that can hold the address of a structure: Student * stuPtr, stu1; Use the & operator to assign an address: stuPtr = & stu1; A structure pointer can be a function parameter
29
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 29 Accessing Structure Members via Pointer Variables Use () to dereference the pointer variable, not the field within the structure: cout << (*stuPtr).studentID; You can use the structure pointer operator ( -> ), a.k.a arrow operator to eliminate use of (*). cout studentID;
30
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 30 10.9 Pointers to Structures You may take the address of a structure variable and create variables that are pointers to structures. Circle *cirPtr; // cirPtr is a pointer to a Circle CirPtr = &piePlate; *cirPtr.radius = 10; // incorrect way to access Radius because the dot operator // has higher precedence than the indirection operator (*cirPtr).radius = 10; //correct access to Radius cirPtr -> radius = 10; // structure pointer operator ( -> ), easier notation for // dereferencing structure pointers
31
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 31 -> is the structure pointer operator. It: (1) dereferences the pointer (to access the structure varible) (2) accesses the structure member. s -> gpa // dereference structure pointer s // access the structure member gpa. (*s).gpa // equivalent expression // easier to see what's happening
32
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 32 10.10 Focus on Software Engineering: When to Use., When to Use ->, and When to Use *
33
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 33 (*s).ms is a structure pointer and m is a member. The * operator dereferences s, causing the expression to access the m member of the structure pointed to by s. This expression is the same as s->m *s->p equivalent to *(*s).p s is a structure pointer and p, a pointer, is a member of the structure pointed to by s. This expression accesses the value pointed to by p. (The -> operator dereferences s and the * operator dereferences p.) *(*s).p equivalent expressions: *((*s).p) *s->p *(s->p) s is a structure pointer and p, a pointer, is a member of the structure pointed to by s. This expression accesses the value pointed to by p. (*s) dereferences s and the outermost * operator dereferences p. This expression is the same as *s->p
34
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 34 10.11 Unions Similar to a struct, but –all members share a single memory location, and –only 1 member of the union can be active at a time Declared using union, otherwise the same as struct Variables defined as for struct variables
35
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 35 Anonymous Union A union without a union tag: union {... }; Must use static if declared outside of a function Allocates memory at declaration time Can refer to members directly without the dot operator Using only 1 memory location saves space.
36
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 36 10.12 Enumerated Data Types An enumerated data type is a programmer- defined data type. It consists of values known as enumerators, which represent integer constants.
37
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 37 Enumerated Data Types Example: enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; The identifiers MONDAY, TUESDAY, WEDNESDAY, THURSDAY, and FRIDAY, which are listed inside the braces, are enumerators. They represent the values that belong to the Day data type. The enumerators are named constants.
38
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 38 Enumerated Data Types enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; Note that the enumerators are not strings, so they aren’t enclosed in quotes. They are identifiers ( named constants ).
39
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 39 Enumerated Data Types Once you have created an enumerated data type in your program, you can define variables of that type. Example: Day workDay; This statement defines workDay as a variable of the Day type.
40
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 40 Enumerated Data Types We may assign any of the enumerators MONDAY, TUESDAY, WEDNESDAY, THURSDAY, or FRIDAY to a variable of the Day type. Example: workDay = WEDNESDAY;
41
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 41 Enumerated Data Types So, what is an enumerator? Think of it as an integer named constant Internally, the compiler assigns integer values to the enumerators, beginning at 0.
42
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 42 Enumerated Data Types enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; In memory... MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4
43
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 43 Enumerated Data Types Using the Day declaration, the following code... cout << MONDAY << " " << WEDNESDAY << " “ << FRIDAY << endl;...will produce this output: 0 2 4
44
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 44 Assigning an integer to an enum Variable You cannot directly assign an integer value to an enum variable. This will not work: workDay = 3;// Error! Instead, you must cast the integer: workDay = static_cast (3);
45
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 45 Assigning an Enumerator to an int Variable You CAN assign an enumerator to an int variable. For example: int x; x = THURSDAY; This code assigns 3 to x.
46
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 46 Comparing Enumerator Values Enumerator values can be compared using the relational operators. For example, using the Day data type the following code will display the message "Friday is greater than Monday.“ if (FRIDAY > MONDAY) { cout << "Friday is greater " << "than Monday.\n"; }
47
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 47 Enumerated Data Types Program 11-13 shows enumerators used to control a loop: // Get the sales for each day. for (index = MONDAY; index > sales[index]; } // Would not work if index was an enumerated type
48
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 48 Anonymous Enumerated Types An anonymous enumerated type is simply one that does not have a name. For example, in Program 11-13 we could have declared the enumerated type as: enum { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };
49
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 49 Using Math Operators with enum Variables You can run into problems when trying to perform math operations with enum variables. For example: Day day1, day2; // Define two Day variables. day1 = TUESDAY; // Assign TUESDAY to day1. day2 = day1 + 1; // ERROR! Will not work! The third statement will not work because the expression day1 + 1 results in the integer value 2, and you cannot store an int in an enum variable.
50
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 50 Using Math Operators with enum Variables You can fix this by using a cast to explicitly convert the result to Day, as shown here: // This will work. day2 = static_cast (day1 + 1);
51
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 51 Using an enum Variable to Step through an Array's Elements Because enumerators are stored in memory as integers, you can use them as array subscripts. For example: enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; const int NUM_DAYS = 5; double sales[NUM_DAYS]; sales[MONDAY] = 1525.00; sales[TUESDAY] = 1896.50; sales[WEDNESDAY] = 1975.63; sales[THURSDAY] = 1678.33; sales[FRIDAY] = 1498.52;
52
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 52 Using an enum Variable to Step through an Array's Elements Remember, though, you cannot use the ++ operator on an enum variable. So, the following loop will NOT work. Day workDay; // Define a Day variable // ERROR!!! This code will NOT work. for (workDay = MONDAY; workDay <= FRIDAY; workDay++) { cout << "Enter the sales for day " << workDay << ": "; cin >> sales[workDay]; }
53
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 53 Using an enum Variable to Step through an Array's Elements You must rewrite the loop’s update expression using a cast instead of ++: for (workDay = MONDAY; workDay <= FRIDAY; workDay = static_cast (workDay + 1)) { cout << "Enter the sales for day " << workDay << ": "; cin >> sales[workDay]; } //Simpler to keep the LCV as an int variable
54
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 54 Enumerators Must Be Unique Within the same Scope Enumerators must be unique within the same scope. For example, an error will result if both of the following enumerated types are declared within the same scope: enum Presidents { MCKINLEY, ROOSEVELT, TAFT }; enum VicePresidents { ROOSEVELT, FAIRBANKS, SHERMAN }; ROOSEVELT is declared twice.
55
4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 10 slide 55 Declaring the Type and Defining the Variables in One Statement You can declare an enumerated data type and define one or more variables of the type in the same statement. For example: enum Car { PORSCHE, FERRARI, JAGUAR } sportsCar; This code declares the Car data type and defines a variable named sportsCar.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.