Note 11.10.1.
Notice that outside of the structure definition, you do need to include the prefix
Time::
at the beginning of each function name!
const
.
.h
instead of .cpp
. For the example we have been looking at, the header file is called Time.h
, and it contains the following:
struct Time {
// instance variables
int hour, minute;
double second;
// constructors
Time(int hour, int min, double secs);
Time(double secs);
// modifiers
void increment(double secs);
// functions
void print() const;
bool after(const Time& time2) const;
Time add(const Time& t2) const;
double convertToSeconds() const;
};
Time::
at the beginning of every function name. The compiler knows that we are declaring functions that are members of the Time
structure.
Time.cpp
contains the definitions of the member functions (I have elided the function bodies to save space):
#include <iostream>
using namespace std;
#include "Time.h"
Time::Time(int h, int m, double s) ...
Time::Time(double secs) ...
void Time::increment(double secs) ...
void Time::print() const ...
bool Time::after(const Time& time2) const ...
Time Time::add(const Time& t2) const ...
double Time::convertToSeconds() const ...
Time.cpp
appear in the same order as the declarations in Time.h
, although it is not necessary.
Time::
at the beginning of each function name!
include
statement. That way, while the compiler is reading the function definitions, it knows enough about the structure to check the code and catch errors.
Time.h
include directive uses quotation marks around the name of the file. The quotation marks tell the compiler that it should look for the file in the same folder as the code. Using < >
tells the compiler it should look for the file in the standard libraries folder that was provided with the compiler.
main.cpp
contains the function main
along with any functions we want that are not members of the Time
structure (in this case there are none):
#include <iostream>
using namespace std;
#include "Time.h"
int main() {
Time currentTime(9, 14, 30.0);
currentTime.increment (500.0);
currentTime.print();
Time breadTime(3, 35, 0.0);
Time doneTime = currentTime.add (breadTime);
doneTime.print();
if (doneTime.after(currentTime)) {
cout << "The bread will be done after it starts." << endl;
}
return 0;
}
main.cpp
has to include the header file.
Time
, you might find it useful in more than one program. By separating the definition of Time
from main.cpp
, you make is easy to include the Time
structure in another program.
Time.cpp
from the programs that use them.
#include <iostream>
using namespace std;
iostream
is the header file that contains declarations for cin
and cout
and the functions that operate on them. When you compile your program, you need the information in that header file.
header.h
, how would I include it in the implementation file?
#include <header.h>
#include <"header.h">
#include header.h
#include "header.h"