A struct in C++ is
a collection of variables that are brought together under one name, thus
providing a convenient method of keeping related information together.
They fall under the category of compound data types because they
consist (typically) of several different, yet logically related, variables.
You should realize that structs are deprecated by (i.e., they are now obsolete
because of) classes, but are nonetheless frequently found in legacy
code (and in C code, which does not have the class construct). Thus,
it is important to understand how they work.
Suppose we want to represent
an automobile. The first step when representing anything is
to figure out exactly what features you are interested in. There
are thousands upon thousands of things related to cars, but we only want
the ones important to us. We'll keep it simple and represent the
folowing aspects of an automobile:
-
make
-
model
-
year
-
maximum occupancy (including
the driver)
-
size of the gas tank
-
horsepower
Surely there are many more things
we could add, but this is dictated by the problem you are trying to solve
(e.g., a car dealer will need to know the cost and the sticker price, while
a mechanic would not care about things like number of cylinders and feul
injection).
Using just regular variables,
we might try something like this in C++:
string make;
string model;
int year;
int maxOccupancy;
double gasTankSize;
int horsepower;
Which is a good start, but only
if you want your program to restrict itself to exactly one car. Suppose
we had another... then we'd have to create a whole new set of variables
with new names!
string make2;
string model2;
int year2;
int maxOccupancy2;
double gasTankSize2;
int horsepower2;
Ugh! What if we have another,
and another? There's got to be a better way, and there is.
In C++, one way to bring these variabels together is to use a struct.
Thus, rather than having 6 separate variables for an automobile, we'll
have one variable per automobile, each of those being a compound type defined
by the following:
struct Automobile {
string make;
// the make of the car ("Dodge", "Saturn", etc.)
string model;
// model of the car ("Corvette", "Dart", etc.)
int year;
// year the car was built
int maxOccupancy; // number of people
that can fit (including driver)
double gasTankSize; // max number of gallons
tank can hold
int horsepower; // of
the engine
}
This defines a new type.
In the context of a program, you can either put struct definitions above
main() (this is a global placement, and is typical for type declarations),
or in the block where you need them, if you only need them locally (like
inside main(), or a function). Note that we are still allowed to
declare multiple variables (fields
Just as we can create variables
of other types, we can now create Automobile variables:
Automobile myCar;
Just as in any declaration,
this results in memory being allocated for a new Automobile variable (called
myCar).
The variables inside the struct are called fields (sometimes referred
to as members). So, year
is a field of Automobile,
for example.
In order to get access to
the fields, you need to use the dot operator (also called the selection
operator), which is denoted by the period ('.').
To use the dot operator,
you first identify the variable you want, insert a period, then put the
name of the field. This is very similar to sending messages to objects
as you've heard about earlier, but even easier. In this case, your
just accessing a variable that is part of a struct. For example,
if we want to assign values to myCar, we might do something like this:
myCar.make = "Chevy";
myCar.model = "Nova";
myCar.year = 1977;
myCar.maxOccupancy = 4;
myCar.gasTankSize = 12.5;
myCar.horsePower = 160;
The fields of myCar can be treated
just like any variable. Examples:
// read a value in for a field
cout << "Enter the year: ";
cin >> myCar.year;
// display a field
cout << "The horsepower is " << myCar.horsepower <<
endl;
// use a field in a conditional
if ((myCar.maxOccupancy > 2) && (myCar.maxOccupancy <=
5))
cout << "This car is classified as a mid-size\n";
// do a calculation (assume other variables have meaningful values)
double gasLeft = myCar.gasTankSize - milesDriven * milesPerGallon;
cout << "You have " << gasLeft << " gallons left
in the car.\n";
It's easy to create several
Automobile variables and use them all:
Automobile auto1, auto2, auto3;
auto1.year = 2000;
auto2.year = auto1.year;
// fill auto2's remaining fields
auto3 = auto2; // all fields get copied here
Finally, here's a little
program that uses a small struct. I suggest copying and pasting this
into a Borland project and playing around with the code.
/* CS401 - Intro to Comp Sci
* summer 2001
*
* this program demonstrates the declaration and use of a
simple
* struct.
*/
#include <iostream>
#include <string>
#include <conio>
using namespace std;
// PersonRec definition
// stores height & weight info about a person
struct PersonRec {
string name;
int height, weight;
}; // <--- NOTE THE SEMI-COLON HERE!!
void displayPerson(ostream&, PersonRec); // displays PersonRecs
bool equalPersons(PersonRec, PersonRec);
int main() {
// create three PersonRecs
PersonRec p1, p2, p3;
// load p1
cout << "Enter name: ";
cin >> p1.name;
cout << "Enter height (in inches): ";
cin >> p1.height;
cout << "Enter weight (in lbs.): ";
cin >> p1.weight;
// load p2
cout << "Loading next person automatically.\n";
p2.name = "Pierre";
p2.height = 73;
p2.weight = 198;
// load p3
cout << "Copying first person rec to third.\n";
p3 = p1;
// a few possible uses of the PersonRecs.
displayPerson(cout, p1);
displayPerson(cout, p2);
cout << "p2's name is " << p2.name <<
endl;
cout << "p1's height is " << p1.height
<< endl;
int combinedWt = p1.weight + p2.weight;
cout << "p1 and p2 combined weight is " <<
combinedWt << endl;
cout << "hit a key...\n";
getch();
// it'd be nice if we could use ==, but it isn't defined
for structs
if (equalPersons(p1,p3))
cout << "p1 and p2 are the
same (should be true)\n";
while (p1.weight < p2.weight) {
cout << "increasing the weight
of p1 by 10.\n";
p1.weight += 10;
}
cout << "p1 now weighs " << p1.weight
<< endl;
if (equalPersons(p1,p3)) // could now be false,
if p1's weight changed
cout << "p1 and p3 are the
same.\n";
else
cout << "p2 and p3 are different.\n";
cout << "hit a key...\n";
getch();
return 0;
}
void displayPerson(ostream& out, PersonRec pr) {
out << "NAME: " << pr.name << endl;
out << " height: " << pr.height
<< endl;
out << " weight: " << pr.weight
<< endl;
}
bool equalPersons(PersonRec pr1, PersonRec pr2) {
return ( (pr1.name == pr2.name)
&& (pr1.height == pr2.height)
&& (pr1.weight == pr2.weight));
} |
and some output:
Enter name: Pavol
Enter height (in inches): 71
Enter weight (in lbs.): 175
Loading next person automatically.
Copying first person rec to third.
NAME: Pavol
height: 71
weight: 175
NAME: Pierre
height: 73
weight: 198
p2's name is Pierre
p1's height is 71
p1 and p2 combined weight is 373
hit a key...
p1 and p2 are the same (should be true)
increasing the weight of p1 by 10.
increasing the weight of p1 by 10.
increasing the weight of p1 by 10.
p1 now weighs 205
p2 and p3 are different.
hit a key...
|
|