Structures and Enumerators
Structures and Enumerators
Structures
7-2
Example struct Declaration
struct Student
{ structure tag
int studentID;
string name; structure members
short year;
double grades[10];
}; Notice the
required
;
7-3
Defining Structure Variables
• struct declaration does not allocate memory or
create variables
s1
• To define variables, use studentID
structure tag as type name name
Student s1; year
grades
7-4
Structure Initialization
Structures can be initialized with a comma separated list
of values, similar to arrays:
7-7
Displaying struct Members
To display the contents of a struct
variable, you must display each field
separately, using the dot operator
Wrong:
cout << s1; // won’t work!
Correct:
cout << s1.studentID << endl;
cout << s1.name << endl;
cout << s1.year << endl;
cout << s1.grades[0];
7-8
Copying structs
• You can copy a struct using the assignment
operator. This performs a memberwise
assignment (each member gets copied).
s2 = s1;
// now s2 has the same values as s1
7-9
Comparing struct Members
7-10
Nested Structures
A structure can have another structure as a
member.
struct Date
{ int day,
month,
year;
};
struct Student
{ int studentID;
string name;
Date birthdate;
double grades[10];
}; 7-11
Members of Nested Structures
Use the dot operator multiple times to
access fields of nested structures
Student s5;
s5.name = “John Smith”;
s5.birthdate.year = 1999;
s5.birthdate.month = 12;
s5.birthdate.day = 25;
7-12
Arrays of Structures
Can create arrays of structures, same as simple types:
struct Student {
string name;
int grade;
};
// create an array of 2 students
Student students[2] = {
{“Jim”, 2},
{“Anne”, 1}
};
You should declare a struct and write your code like this:
struct Student
{
string name;
int grade;
};
Student students[MAX_STUDENTS];
7-14
Example
struct Date struct Student
{ int day, { string name;
month, Date birthdate;
year; double grades[10];
}; };
Student students[100];
7-24