STRUCTA structure is
simply a way of grouping several variables under one name. When you
declare a structure type you use the struct keyword, followed by
what you want to call this, then an opening curly brace, then the
variables you want grouped under this structure type, and lastly a
closing curly brace with a semi-colon. All this sounds so darn
complicated. But I'll give an example. We create a structure type
that contains three pieces (three variables), year, month, and day:
struct date
{
int year;
int month;
int day;
};
How can we use it?
The following example does not contain a struct. It declares
three integer variables that make up a date (year, month, and day)
and then gets user input to fill these variables with values.
/* -example
1--------------------------------------------------------------- */
#include <iostream.h>
void main()
{
int year, month, day;
cout << "Please input the following: ";
cout << "Year :";
cin >> year;
cout << "Month :";
cin >> month;
cout << "Day :";
cin >> day;
}
/*
-------------------------------------------------------------------------
*/
Now the following is an example program that does the same thing
except it uses a structure.
/*
-example-2---------------------------------------------------------------
*/
#include <iostream.h>
struct date
{
int year;
int month;
int day;
};
void main()
{
date dt;
cout << "Please input the following: ";
cout << "Year :";
cin >> dt.year;
cout << "Month :";
cin >> dt.month;
cout << "Day :";
cin >> dt.day;
}
/*
-------------------------------------------------------------------------
*/
We declared the structure date to contain three pieces, which of
course are year, month, and day. Now then in main() we create a
variable called dt using our date structure. In essence this creates
those three pieces under that one name. So dt has three pieces that
call it momma:
dt
|-- year
|-- month
\-- day
Now we can use these pieces almost just like normal variables.
Because that's all they are! They're normal variables just "grouped"
under the one object dt. To access variables within a structure you
put the name of the struct followed by a period (.) and then lastly
the name of the variable within that you wish to access:
[struct].[variable]
So say we want to use the year part of dt: dt.year. Or month:
dt.month.
that does the same thing except it uses a structure.
How does this become useful to us? Well, what if you want to have
the date of birth for three people. You could do it without structs
but it requires us to declare many variables even though each
person's date of birth contain common things.
|