Section 1.10 One last example
The final example weβll look at is
addTime
:
Time addTime2(const Time& t1, const Time& t2) {
double seconds = convertToSeconds(t1) + convertToSeconds(t2);
return makeTime(seconds);
}
We have to make several changes to this function, including:
-
Replace the first parameter with an implicit parameter, which should be declared
const
. -
Replace the use of
makeTime
with a constructor invocation.
Hereβs the result:
Time Time::add(const Time& t2) const {
double seconds = convertToSeconds() + t2.convertToSeconds();
Time time(seconds);
return time;
}
The first time we invoke
convertToSeconds
, there is no apparent object! Inside a member function, the compiler assumes that we want to invoke the function on the current object. Thus, the first invocation acts on this
; the second invocation acts on t2
.
The next line of the function invokes the constructor that takes a single
double
as a parameter; the last line returns the resulting object.
add
function in this active code!#include <iostream>
using namespace std;
struct Time {
int hour, minute;
double second;
Time(double secs);
Time(int h, int m, double s);
bool after(const Time& time2) const;
Time add(const Time& t2) const;
double convertToSeconds() const;
void print();
};
int main() {
Time t1(9, 20, 0.0); cout << "t1 = "; t1.print(); cout << endl;
Time t2(7, 30, 0.0); cout << "t2 = "; t2.print(); cout << endl;
Time t3 = t1.add(t2);
cout << "Time t1 + Time t2 = "; t3.print(); cout << endl;
}
Checkpoint 1.10.2.
Checkpoint 1.10.3.
You have attempted of activities on this page.