====================================================================== Faculty of Applied Science and Engineering, University of Toronto CSC181: Introduction to Computer Programming, Fall 2000 Tutorial Notes, Week 11 ====================================================================== ----------------- Summary of Topics ----------------- - C++ classes ------- Example ------- The following program models students who have the following attributes: - a student ID - a name - a list of marks It is essentially the C++ equivalent of the program from Week 4, which used structs. ---- Code ---- #include #include #define NAME_LENGTH (20) #define MARKS_LENGTH (10) class Student { friend ostream& operator<< (ostream& os, const Student& s); private: int id; char name[NAME_LENGTH]; int marks[MARKS_LENGTH]; int marksSize; public: Student(const int id, const char* name); int Student::getId() const; const char* Student::getName() const; void addMark(const int mark); double getAverage() const; }; Student::Student(const int i, const char* n) { id = i; strcpy(name, n); marksSize = 0; } void Student::addMark(const int m) { marks[marksSize] = m; marksSize++; } int Student::getId() const { return id; } const char* Student::getName() const { return name; } double Student::getAverage() const { if (marksSize == 0) { return 0.0; } else { int sum = 0; int i; for (i = 0; i != marksSize; i++) { sum += marks[i]; } return (double)sum/marksSize; } } ostream& operator<< (ostream& os, const Student& s) { os << "{id = " << s.getId() << ", name = " << s.getName(); os << ", average = " << s.getAverage(); os << ", marksSize = " << s.marksSize << "}"; return os; } int main(void) { Student s(3, "bob"); cout << "ID = " << s.getId() << endl; cout << "Name = " << s.getName() << endl; cout << "Average = " << s.getAverage() << endl; s.addMark(80); cout << "Average = " << s.getAverage() << endl; s.addMark(70); s.addMark(92); cout << "Average = " << s.getAverage() << endl; cout << s << endl; return 0; }