Structures


In C++ structures should be one of the early topics studied. The reason for this is that in C++ structures and their extension: classes are the major characteristics that set C++ apart from most other languages. Structures are the first step to classes and classes are what permit C++ to be an OOP language.

In reading many books on C++ you may be lead to believe that there is a significant difference between structures and classes. The reason for this is that many authors and programmers restrict their discussion of structures further than C++ syntax requires. Many authors say that structures only deal with data while classes deal with data and with functions that manipulate this data. However in C++ structures may be defined to have functions just like classes. The only differences between these two constructs are minor ones. The differences lie in their respective defaults. These differences will be discussed later. To illustrate that a structure may have functions as well as classes, the following discussion will close with an illustration that includes functions in a structure.

When a structure is defined, the keyword struct is required. As with an enumerated data type a Tag may be left off. (i.e. it is possible to have anonymous structures.) The abstract construct of the definition of a structure is:

image from book

 struct Tag {    member list }; 

image from book

 Note:  Currently it is recommended that the structure's name start with a cap.

Within the body of the structure definition is a member list of declarations of the variables of the structure (This is considered to be a declaration rather than a definition because memory is not assigned to these variable until an instance of the structure is defined.) The variables in the member list are referred to as members or data members and sometimes also called attributes or fields.

When a variable (called an instance of the structure) of this data type is defined, it is assigned a "slice" of memory large enough to contain memory for each of its members. The definition of a structure instance is similar to the definition of a variable of a system data type. That is, the general construct of an instance definition is the following:

image from book

 Tag instanceName; 

image from book

 Note:  While an array permits the joining of units of memory into a block as a structure does, all of the array's elements are of the same data type. Structures on the other hand permit the joining of memory into blocks of data that may be of varying sizes.

In C++, structures and instances of the structure are created/defined as in the following example:

image from book

 struct Date {    int theMonth;    int theDay;    int theYear; }; Date invoiceDate,      shippingDate; 

image from book

An instance of a structure may access its data member when used for input or output by using the dot operator as in the following:

image from book

 cout << "What is the shipping date? "; cin >> shippingDate.theMonth >> dash >> shippingDate.theDay     >> dash >> shippingDate.theYear; cout << endl << "Did you say that the shipping date is "      << shippingDate.theMonth << "/" << shippingDate.theDay      << "/" << shippingDate.theYear << endl; 

image from book

Notice how an instance of a structure may access it data members as in the following example: struct3.cpp. Also note in this example that the size of a structure instance is greater than or equal to the sum of the sizes of the individual data members.

In the example above with the structure Date, all three members are of the same data type similar to an array. However, they may be of different data types. The members of a structure can be of any data type including enumerated data types or even other structures. Notice in the example below that the data members may be arrays as well as any one of the system data types.

image from book

 struct stuff { char name[30];    float price; }; stuff item1 = {"Widget", 5.75}; stuff item2; item2 = item1; cout << "The name of item 1 is " << item1.name << endl       << "The price of item 1 is " << item1.price << endl       << "The name of item 2 is " << item2.name << endl       << "The price of item 2 is " << item2.price << endl; 

image from book

For this example see STRUCT2.CPP.

As stated above, the data members of a structure may be one of the system data types, and in addition the data member may be instances of enumerated data types or instances of another structure as in the following example:

image from book

 enum workType {salaried, hourly}; struct Date {    int theMonth,    theDay,    theYear; }; struct Employee {    Date      hireDate;    workType  salaryType;    char       employeeLastName[15],               employeeFirstName[10];    float      unitPay; }; void main() {   char dash;   Employee newStaff; // Following two lines are not valid so must use next one // try to remove the comments. // // Employee oldStaff; // oldStaff = { {6,12,70}, salaried, "Thomas", "John", 350.00};   Employee oldStaff = { {6,12,70}, salaried, "Thomas", "John", 350.00};   cout << "The name of the last employee was "        << oldStaff.employeeLastName        << ", " << oldStaff.employeeFirstName << "." << endl        << "Hired on " << oldStaff.hireDate.theMonth << "/"        << oldStaff.hireDate.theDay << "/"        << oldStaff.hireDate.theYear << "." << endl;   if (oldStaff.salaryType==salaried)      cout << "and was salaried at $" << setiosflags(ios::fixed)           << setprecision(2) << setiosflags(ios::showpoint)           << oldStaff.unitPay << endl;   else      cout << "and was hourly at $" << setiosflags(ios::fixed)           << setprecision(2) << setiosflags(ios::showpoint)           << oldStaff.unitPay << endl << endl;   cout << endl << endl << endl << "What is the new employee's name? ";   cin >> newStaff.employeeFirstName >> newStaff.employeeLastName;   cout << endl << endl << "What is the pay per unit of work? ";   cin >> newStaff.unitPay;   cout << endl << endl << "What was the hire date? ";   cin >> newStaff.hireDate.theMonth >> dash       >> newStaff.hireDate.theDay >> dash       >> newStaff.hireDate.theYear;   int salary;   cout << endl << endl << "Is the employee salaried (0) or hourly (1)? ";   cin >> salary;   newStaff.salaryType= static_cast<workType>(salary);   cout << endl << endl << "The name of the new employee is "        << newStaff.employeeFirstName        << " " << newStaff.employeeLastName << "." << endl        << "Hired on " << newStaff.hireDate.theMonth << "/"        << newStaff.hireDate.theDay << "/"        << newStaff.hireDate.theYear << "." << endl;   if (newStaff.salaryType==salaried)      cout << "and is salaried at $" << setiosflags(ios::fixed)            << setprecision(2) << setiosflags(ios::showpoint)            << newStaff.unitPay << endl;   else      cout << "and is hourly at $" << setiosflags(ios::fixed)            << setprecision(2) << setiosflags(ios::showpoint)            << newStaff.unitPay << endl;   cout << endl << endl; } 

image from book

You will notice in the example above that oldStaff is assigned values as it is defined. In C++ it is possible to load an instance with data when the instance of the structure is defined. However this assignment is only possible when the instance is being defined. While this is true, it is possible to assign one instance to another. For example (see STRUCT1.CPP).

C++ structures can be created without a tag or structure name as long as the definition creates at least one instance of that structure as in the following example:

image from book

 struct {    int theMonth;    int theDay;    int theYear; } invoiceDate; void main() {   char dash;   cout << "What is the invoice date? ";   cin >> invoiceDate.theMonth >> dash >> invoiceDate.theDay       >> dash >> invoiceDate.theYear;   cout << endl << "Did you say that the invoice date is "        << invoiceDate.theMonth << "/" << invoiceDate.theDay        << "/" << invoiceDate.theYear << endl; } 

image from book

For an example of this anonymous structure, see STRUCT4.CPP.

In the example STRUCT1.CPP above, two of the data members were arrays. In addition to having arrays as data members of a structure, it is also possible to have arrays of instances of a structure. Suppose there was a structure Quizzes that worked with the students in this class. Suppose that the program would handle at most 30 students. Therefore each instance would contain the student's name and a grade for each of five quizzes. For example the structure Quizzes could be defined as following

image from book

 struct Quizzes {    string firstName;    string lastName;    int quizGrades[5]; }; 

image from book

Now the program would need to contain an array with 30 Quizzes instances in it as in the following definition:

image from book

 Quizzes students[30]; 

image from book

To complete the program the functions enterStudents() and calculateAverages() could be defined as in the following:

image from book

 int enterStudents(Quizzes students[ ]) {   char resp;   for(int index = 0; index < 30 ; ++index)   {      cout << "What is student " << index + 1 << "\'s first name? ";      cin >> students[index].firstName;      cout << "What is student " << index + 1 << "\'s last name? ";      cin >> students[index].lastName;      cout << endl;      for(int jindex = 0 ; jindex < 5; ++jindex)      {        cout << "What is " << students[index].firstName + " "                                 + students[index].lastName                           << "\'s grade on quiz " << jindex + 1 << "? ";        cin >> students[index].quizGrades[jindex];      }      resp = 'y';      if(index < 29)      {         cout << endl << "Another student (Y/N)? ";         cin >> resp;      }      if(resp =='N' || resp =='n')      {         ++index;         break;      }      clearScreen();   }   return index; } 

image from book

and

image from book

 void calculateAverages(Quizzes students[ ],int numberStudents) {   for(int index = 0; index < numberStudents; ++ index)   {     int sumQuizzes = 0;     for(int jindex = 0; jindex < 5; ++jindex)     {       sumQuizzes += students[index].quizGrades[jindex];     }     cout << students[index].firstName + " " + students[index].lastName          << "\'s average is "<< sumQuizzes/5.0 << endl ;   } } 

image from book

Recall that arrays are passed as references into a function and therefore the elements of an array may be changed in the body of a function. See STUDENTGRADES.CPP.

 Note:  The function clearScreen() listed above does as its name says, it clears the screen. In Visual Studio .NET 2005, this could also be done with the following code: system("cls");




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net