Sams Teach Yourself C++ in 21 Days

(singke) #1
Assume for a moment that you have five functions named fOnePrint,fTwoPrint,
fThreePrint,fFourPrint, and fFivePrint. You can then declare
#define fPRINT(x) f ## x ## Print
and then use it with fPRINT(Two)to generate fTwoPrintand with fPRINT(Three)to
generate fThreePrint.
At the conclusion of Week 2, a PartsListclass was developed. This list could only han-
dle objects of type List. Suppose that this list works well, and you want to be able to
make lists of animals, cars, computers, and so forth.
One approach is to create AnimalList,CarList,ComputerList, and so on, cutting and
pasting the code in place. This quickly becomes a nightmare because every change to
one list must be written to all the others.
An alternative is to use macros and the concatenation operator. For example, you could
define
#define Listof(Type) class Type##List \
{ \
public: \
Type##List(){} \
private: \
int itsLength; \
};
This example is overly sparse, but the idea is to put in all the necessary methods and
data. When you are ready to create an AnimalList, you write
Listof(Animal)
and this is turned into the declaration of the AnimalListclass. Some problems occur
with this approach, all of which were discussed in detail on Day 19, “Templates.”

Predefined Macros ..............................................................................................


Many compilers predefine a number of useful macros, including __DATE__,__TIME__,
__LINE__, and __FILE__. Each of these names is surrounded by two underscore charac-
ters to reduce the likelihood that the names will conflict with names you’ve used in your
program.
When the precompiler sees one of these macros, it makes the appropriate substitutes.
For__DATE__, the current date is substituted. For __TIME__, the current time is substi-
tuted. __LINE__and __FILE__are replaced with the source code line number and file-
name, respectively. You should note that this substitution is made when the source is

760 Day 21

Free download pdf