Sams Teach Yourself C++ in 21 Days

(singke) #1
LISTING6.7 CatImplementation in Cat.cpp
1: // Demonstrates inline functions
2: // and inclusion of header files
3: // be sure to include the header files!
4: #include “Cat.hpp”
5:
6:
7: Cat::Cat(int initialAge) //constructor
8: {
9: itsAge = initialAge;
10: }
11:
12: Cat::~Cat() //destructor, takes no action
13: {
14: }
15:
16: // Create a cat, set its age, have it
17: // meow, tell us its age, then meow again.
18: int main()
19: {
20: Cat Frisky(5);
21: Frisky.Meow();
22: std::cout << “Frisky is a cat who is “ ;
23: std::cout << Frisky.GetAge() << “ years old.\n”;
24: Frisky.Meow();
25: Frisky.SetAge(7);
26: std::cout << “Now Frisky is “ ;
27: std::cout << Frisky.GetAge() << “ years old.\n”;
28: return 0;
29: }

Meow.
Frisky is a cat who is 5 years old.
Meow.
Now Frisky is 7 years old.
The code presented in Listing 6.6 and Listing 6.7 is similar to the code in Listing
6.4, except that three of the methods are written inline in the declaration file and
the declaration has been separated into Cat.hpp(Listing 6.6).
GetAge()is declared on line 6 of Cat.hpp, and its inline implementation is provided.
Lines 7 and 8 provide more inline functions, but the functionality of these functions is
unchanged from the previous “outline” implementations.
Line 4 of Cat.cpp(Listing 6.7) shows #include “Cat.hpp”, which brings in the listings
from Cat.hpp. By including Cat.hpp, you have told the precompiler to read Cat.hppinto
the file as if it had been typed there, starting on line 5.

OUTPUT


164 Day 6


ANALYSIS
Free download pdf