Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 13: Making Classes Work 177

class Student

{

public:

int semesterHours; float gpa;

// add a completed course to the record float addCourse(int hours, float grade)

{

//call some external function to calculate the

//weighted grade

float weightedGPA = ::addCourse(semesterHours, gpa);

//now add in the new course semesterHours += hours;

//use the same function to calculate the

//weighted grade of this new course weightedGPA += ::addCourse(hours, grade); gpa = weightedGPA / semesterHours;

//return the new gpa

return gpa;

}

};

This is just like when I call out the name “Stephen” in my own home; every­ one assumes that I mean me — they default the Davis onto my name. If I mean some other Stephen out there outside my family, I need to say “Stephen Smith,” or “Stephen Jones,” or whatever. That’s what the scope resolution operator does.

The extended name of a function includes its arguments. Now you’ve added the class name to which the function belongs.

Defining a Member Function in the Class

A member function can be defined either in the class or separately. When defined in the class definition, the function looks like the following contained in the include file Savings.h.

//Savings - define a class that includes the ability

//to make a deposit

class Savings

{

public:

178 Part III: Introduction to Classes

// declare but don’t define member function float deposit(float amount);

unsigned int accountNumber; float balance;

};

Using an include like this is pretty slick. Now a program can include the class definition (along with the definition for the member function), as follows in the venerable SavingsClass_inline program:

//

//SavingsClassInline - invoke a member function that’s

//

both declared and defined within

//

the class Student

//

 

#include <cstdio>

 

#include <cstdlib>

 

#include <iostream>

 

using namespace std;

 

#include “Savings.h”

 

int main(int nNumberofArgs, char* pszArgs[])

{

Savings s; s.accountNumber = 123456; s.balance = 0.0;

// now add something to the account

cout << “Depositing 10 to account “ << s.accountNumber << endl;

s.deposit(10);

cout << “Balance is “ << s.balance << endl;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

This is cool because everyone other than the programmer of the Savings class can concentrate on the act of performing a deposit rather the details of banking. These have been neatly tucked away in their own include files.

The #include directive inserts the contents of the file during the compila­ tion process. The C++ compiler actually “sees” your source file with the Savings.h file included.

Chapter 13: Making Classes Work 179

Inlining member functions

Member functions defined in the class default to inline (unless they have been specifically out­ lined by a compiler switch or because they con­ tain a loop). Mostly, this is because a member function defined in the class is usually very small, and small functions are prime candidates for inlining.

The content of an inline function is inserted wherever it is invoked. An inline function exe­ cutes faster because the processor doesn’t have to jump over to where the function is defined — inline functions take up more memory because they are copied into every call instead of being defined just once.

There is another good but more technical reason to inline member functions defined within a class. Remember that C structures are normally defined in include files, which are then included in the .C source files that need them. Such include files should not contain data or functions because these files are compiled mul­ tiple times. Including an inline function is okay, however, because it (like a macro) expands in place in the source file. The same applies to C++ classes. By defaulting member functions defined in classes inline, the preceding problem is avoided.

Keeping a Member Function After Class

For larger functions, putting the code directly in the class definition can lead to some very large, unwieldy class definitions. To prevent this, C++ lets you define member functions outside the class.

A function that is defined outside the class is said to be an outline function. This term is meant to be the opposite of an inline function that has been defined within the class.

When written outside the class declaration, the Savings.h file declares the deposit() function without defining it as follows:

//Savings - define a class that includes the ability

//to make a deposit

class Savings

{

public:

// declare but don’t define member function float deposit(float amount);

unsigned int accountNumber; float balance;

};

180 Part III: Introduction to Classes

The definition of the deposit() function must be included in one of the source files that make up the program. For simplicity, I define the functions within the same SavingsClassOutline.cpp file that contains main().

You would not normally combine the member function definition with the rest of your program. It is more convenient to collect the outlined member function definitions into a source file with an appropriate name (like Savings.cpp).

This source file is combined with other source files as part of building the exe­ cutable program. I describe this in Chapter 22.

//

//SavingsClassOutline - invoke a member function that’s

//

declared within a class but defined

//

in a separate file

//

 

#include <cstdio>

 

#include <cstdlib>

 

#include <iostream>

 

using namespace std;

 

#include “Savings.h”

 

//define the member function Savings::deposit()

//(normally this is contained in a separate file that is

//then combined with a different file that is combined) float Savings::deposit(float amount)

{

balance += amount; return balance;

}

//the main program

int main(int nNumberofArgs, char* pszArgs[])

{

Savings s; s.accountNumber = 123456; s.balance = 0.0;

// now add something to the account

cout << “Depositing 10 to account “ << s.accountNumber << endl;

s.deposit(10);

cout << “Balance is “ << s.balance << endl;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}