Professional Documents
Culture Documents
1 Structures 551
Initializing Structures
You can initialize a structure at the time that it is declared. To give a structure
variable a value, you follow it by an equal sign and a list of the member values
enclosed in braces. For example, the following definition of a structure type
for a date was given in the previous subsection:
struct Date
{
int month;
int day;
int year;
};
Once the type Date is defined, you can declare and initialize a structure
variable called due_date as follows:
Date due_date = {12, 31, 2004};
Be sure to notice that the initializing values must be given in the order that
corresponds to the order of member variables in the structure type definition.
In this example, due_date.month receives the first initializing value of 12,
due_date.day receives the second value of 31, and due_date.year receives
the third value of 2004.
It is an error if there are more initializers than struct members. If
there are fewer initializer values than struct members, the provided values
are used to initialize data members, in order. Each data member without
an initializer is initialized to a zero value of an appropriate type for the
variable.
Self- T e st Exerc is es
what is the type of each of the following? Mark any that are not correct.
a. account.balance
b. account.interest_rate
552 Chapter 10 / Defining Classes
c. TermAccount.term
d. savings_account.initial1
e. account.initial2
f. account
Given this structure type definition, what will be the output produced by
the following code?
ShoeType shoe1, shoe2;
shoe1.style ='A';
shoe1.price = 9.99;
cout << shoe1.style << " $" << shoe1.price << endl;
shoe2 = shoe1;
shoe2.price = shoe2.price/9;
cout << shoe2.style << " $" << shoe2.price << endl;
9. Give the structure definition for a type named StockRecord that has two
member variables, one named shoe_info of the type ShoeType given in
Self-Test Exercise 2 and one named arrival_date of type Date given in
Self-Test Exercise 5.