11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

176Part III: Introduction to ClassesNormally the :: operator is optional, but there are a few occasions when thisis not so, as illustrated here:// addCourse - combine the hours and grade into// a weighted gradefloat addCourse(int hours, float grade){return hours * grade;}class Student{public:int semesterHours;float gpa;// add a completed course to the recordfloat addCourse(int hours, float grade){// call some external function to calculate the// weighted gradefloat weightedGPA = addCourse(semesterHours, gpa);// now add in the new coursesemesterHours += hours;// use the same function to calculate the weighted// grade of this new courseweightedGPA += addCourse(hours, grade);gpa = weightedGPA / semesterHours;};}// return the new gpareturn gpa;Here, I want the member function Student::addCourse() to call the nonmemberfunction ::addCourse(). Without the :: operator, however, a callto addCourse() from Student refers to Student::addCourse().One member of the family can use the short name when referring to anothermember 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 frontdirects the call to the global version, as desired:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!