|
|
|
|
|
|
|
You can also put the definition of a function into the declaration of the class, which automatically makes that function inline. For example: |
|
|
|
|
|
|
|
|
class Cat
{
public:
int GetWeight() const { return itsWeight; } // inline
void SetWeight(int aWeight);
}; |
|
|
|
|
|
|
|
|
Note the syntax of the GetWeight() definition. The body of the inline function begins immediately after the declaration of the class method; there is no semicolon after the parentheses. Like any function, the definition begins with an opening brace and ends with a closing brace. As usual, whitespace doesn't matter; you could have written the declaration as |
|
|
|
|
|
|
|
|
class Cat
{
public:
int GetWeight() const
{
return itsWeight;
} // inline
void SetWeight(int aWeight);
}; |
|
|
|
|
|
|
|
|
Listings 7.1 and 7.2 re-create the Cat class, but they put the declaration in CAT.HPP and the implementation of the functions in CAT.CPP. Listing 7.1 also changes both the accessor functions and the Meow() function to inline. |
|
|
|
|
|
|
|
|
LISTING 7.1Cat CLASS DECLARATION INCAT.HPP |
|
|
|
 |
|
|
|
|
1: #include <iostream.h>
2: class Cat
3: {
4: public:
5: Cat (int initialAge);
6: ~Cat();
7: int GetAge() const { return itsAge;} // inline!
8: void SetAge (int age) { itsAge = age;} // inline!
9: void Meow() const { cout << Meow.\n;} // inline!
10: private:
11: int itsAge;
12: }; |
|
|
|
|
|