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

Chapter 13: Making Classes Work 171

Naming class members

A member function is a lot like a member of a family. The full name of the function addCourse(int, float) is Student::addCourse(int, float), just as my full name is Stephen Davis. The short name of the function is addCourse(int, float), just as my short name is Stephen. The class name at the beginning of the full name indicates that the function is a member of the class Student. (The :: between the class name and the function name is simply a separator.) The name Davis on the end of my name indicates that I am a member of the Davis family.

Another name for a full name is extended name.

You can define an addCourse(int, float) function that has nothing to do with Student — there are Stephens out there who have nothing to do with my family. (I mean this literally: I know several Stephens who want nothing to do with my family.)

You could have a function Teacher::addCourse(int, float) or even Golf::addCourse(). A function addCourse(int, float) without a class name is just a plain ol’ conventional non-member function.

The extended name for the non-member function is ::addCourse(int, float). (Note the colon without a family name in front.)

Calling a Member Function

Before you look at how to call a member function, remember how to access a data member:

class Student

{

public:

int semesterHours; float gpa;

};

Student s; void fn(void)

{

// access data members of s s.semesterHours = 10;

s.gpa

= 3.0;

}

172 Part III: Introduction to Classes

Notice that you have to specify an object along with the member name. In other words, the following makes no sense:

Student s; void fn(void)

{

// neither of these is legal

semesterHours = 10; // member of what object of what

// class?

Student::semesterHours = 10; // okay, I know the class // but I still don’t know // the object

}

Accessing a member function

Remember that member functions function like data members functionally. The following CallMemberFunction shows how to invoke the member func­ tion addCourse():

//

//CallMemberFunction - define and invoke a function that’s

//

a member of the class Student

//

 

#include <cstdio>

 

#include <cstdlib>

 

#include <iostream>

 

using namespace std;

 

class Student

{

public:

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

{

//calculate the sum of all courses times

//the average grade

float weightedGPA;

weightedGPA = semesterHours * gpa;

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

gpa = weightedGPA / semesterHours;

//return the new gpa

return gpa;

Chapter 13: Making Classes Work 173

}

int semesterHours; float gpa;

};

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

{

Student s; s.semesterHours = 10;

s.gpa

= 3.0;

// the values before the call

cout << “Before: s = (“ << s.semesterHours

<<“, “ << s. gpa

<<endl;

//the following subjects the data members of the s

//object to the member function addCourse() s.addCourse(3, 4.0); // call the member function

//the values are now changed

cout << “After: s = (“ << s.semesterHours

<<“, “ << s. gpa

<<“)” << endl;

//access another object just for the heck of it Student t;

t.semesterHours = 6;

t.gpa

= 1.0;

//

not doing so good

t.addCourse(3, 1.5);

//

things aren’t getting any better

//wait until user is ready before terminating program

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

return 0;

}

The syntax for calling a member function looks like a cross between the syntax for accessing a data member and that used for calling a function. The right side of the dot looks like a conventional function call, but an object is on the left of the dot.

We say that “addCourse() operates on the object s” or, said another way, s is the student to which the course is to be added. You can’t fetch the number of semester hours without knowing from which student — you can’t add a stu­ dent to a course without knowing which student to add. Calling a member func­ tion without an object makes no more sense than referencing a data member without an object.

174 Part III: Introduction to Classes

Accessing other members from a member function

I can see it clearly: You repeat to yourself, “Accessing a member without an object makes no sense. Accessing a member without an object. Accessing . . .” Just about the time you’ve accepted this, you look at the member function

Student::addCourse() and Wham! It hits you: addCourse() accesses other class members without reference to an object. Just like the TV show: “How Do They Do That?”

Okay, which is it, can you or can’t you? Believe me, you can’t. When you ref­ erence a member of Student from addCourse(), that reference is against the Student object with which the call to addCourse() was made. Huh? Go back to the CallMemberFunction example. The critical subsections appear here:

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

{

Student s; s.semesterHours = 10;

s.gpa

= 3.0;

s.addCourse(3, 4.0); // call the member function

Student t; t.semesterHours = 6;

t.gpa = 1.0; // not doing so good t.addCourse(3, 1.5); // things aren’t getting any better

system(“PAUSE”); return 0;

}

When addCourse() is invoked with the object s, all of the otherwise unquali­ fied member references in addCourse() refer to s as well. Thus, the refer­ ence to semesterHours in addCourse() refers to s.semesterHours, and gpa refers to s.gpa. But when addCourse() is invoked with the Student t object, these same references are to t.semesterHours and t.gpa instead.

The object with which the member function was invoked is the “current” object, and all unqualified references to class members refer to this object. Put another way, unqualified references to class members made from a member function are always against the current object.

Chapter 13: Making Classes Work 175

Naming the current object

How does the member function know what the current object is? It’s not magic — the address of the object is passed to the member function as an implicit and hidden first argument. In other words, the following conversion is taking place:

s.addCourse(3, 2.5) is like

Student::addCourse(&s, 3, 2.5)

(Note that you can’t actually use the syntax on the right; this is just the way C++ sees it.)

Inside the function, this implicit pointer to the current object has a name, in case you need to refer to it. It is called this, as in “Which object? This object.” Get it? The type of this is always a pointer to an object of the appropriate class.

Anytime a member function refers to another member of the same class without providing an object explicitly, C++ assumes “this.” You also can refer to this explicitly, if you like. You could

have written Student::addCourse() as follows:

float Student::addCourse(int hours, float grade)

{

float weightedGPA; weightedGPA = this- >semesterHours * this->gpa;

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

weightedGPA += hours * grade;

this->gpa = weightedGPA / this->semesterHours; return this->gpa;

}

The effect is the same whether you explicitly include “this,” as in the preceding example, or leave it implicit, as you did before.

Scope Resolution (And I Don’t Mean How Well Your Microscope Works)

The :: between a member and its class name is called the scope resolution operator because it indicates the scope to which class a member belongs. The class name before the colon is like the family last name, while the func­ tion name after the colons is like the first name — the order is similar to an oriental name, family name first.

You use the :: operator to describe a non-member function by using a null class name. The non-member function addCourse, for example, can be referred to as ::addCourse(int, float), if you prefer. This is like a func­ tion without a home.

176 Part III: Introduction to Classes

Normally the :: operator is optional, but there are a few occasions when this is not so, as illustrated here:

//addCourse - combine the hours and grade into

//a weighted grade

float addCourse(int hours, float grade)

{

return hours * grade;

}

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;

}

};

Here, I want the member function Student::addCourse() to call the non­ member function ::addCourse(). Without the :: operator, however, a call to addCourse() from Student refers to Student::addCourse().

One member of the family can use the short name when referring to another member of the same family. The family . . . I mean class name . . . is understood.

Not indicating the class name in this case results in the function calling itself, which is generally not a good thing. Adding the :: operator to the front directs the call to the global version, as desired: