9.1. time¶
As a second example of a user-defined structure, we will define a type
called time, which is used to record the time of day. The various
pieces of information that form a time are the hour, minute and second,
so these will be the instance variables of the structure.
The first step is to decide what type each instance variable should be.
It seems clear that hour and minute should be integers. Just to
keep things interesting, let’s make second a double, so we can
record fractions of a second.
The active code below shows what the structure definition looks like.
We can create a time object in the usual way.
1#include <iostream>
2
3struct time {
4 int hour, minute;
5 double second;
6};
7
8int main() {
9 time time = { 11, 59, 3.14159 };
10 std::cout << time.hour << ':' << time.minute << ':' << time.second;
11}
The state diagram in Fig. 9.1 shows this object:
Fig. 9.1 Time object state diagram¶
The word instance is sometimes used when we talk about objects, because every object is an instance (or example) of some type. The reason that instance variables are so-named is that every instance of a type has a copy of the instance variables for that type.
Q1
Click on all the statements that are variables of type price. If you make a mistake you can click on the statement again to unhighlight it.
}Variables use a type, they are not part of the type.
Variables use a type, they are not part of the type.
Variables use a type, they are not part of the type.
Variables use a type, they are not part of the type.
Variables use a type, they are not part of the type.
Correct.
Correct.
Correct.
Q2
Click on all the statements that are instance variables of type price.
}Try again.
Correct.
Correct.
Try again.
Try again.
Try again.
Try again.
Try again.
Q3
Try writing the print_time function in the commented section
of the active code below. print_time should print out the time
in the HOUR:MINUTE:SECONDS format. If you get stuck, you can reveal the extra problem
at the end for help.
1#include <iostream>
2
3struct time {
4 int hour;
5 int minute;
6 double second;
7};
8
9void print_time(time& time) {
10 // ``print_time`` should print out the time in the
11 // HOUR:MINUTE:SECONDS format. Write your implementation here.
12}
13
14int main() {
15 time time = { 11, 59, 3.14159 };
16
17 // Should output "11:59:3.14159"
18 print_time(time);
19}
Reveal Problem
Let's write the code for the print_time function. print_time
should print out the time in the HOUR:MINUTE:SECONDS format.
-
cout << hour << ':' << minute << ':' << second; } -
cout << time.hour << ':' << time.minute << ':' << time.second; -
time print_time(time& time) { -
void print_time(time& time) {