// COURSE.H - Course class defintion #ifndef COURSE_H #define COURSE_H #include <iostream.h> #include <string.h> const unsigned CourseNameSize = 10; class Course { public: Course(); Course( const char * nam, char sect, unsigned cred ); // Construct a course from a name, section letter, // and number of credits. unsigned GetCredits() const; // Get the number of credits. void SetCredits( unsigned cred ); // Set the number of credits. friend ostream & operator <<( ostream & os, const Course & C ); friend istream & operator >>( istream & input, Course & C ); private: char name[CourseNameSize]; // course name char section; // section (letter) int credits; // number of credits }; inline unsigned Course::GetCredits() const { return credits; } inline void Course::SetCredits( unsigned cred ) { credits = cred; } #endif
// REGIST.H - Registration class definition #ifndef REGIST_H #define REGIST_H #include <iostream.h> #include "course.h" const unsigned MaxCourses = 10; class Registration { public: Registration(); unsigned GetCredits() const; unsigned GetCount() const; friend ostream & operator <<( ostream & os, const Registration & R); friend istream & operator >>( istream & input, Registration & R ); private: long studentId; // student ID number unsigned semester; // semester year, number unsigned count; // number of courses Course courses[MaxCourses]; // array of courses }; inline unsigned Registration::GetCount() const { return count; } #endif
istream & operator >>( istream & input, Registration & R ) { input >> R.studentId >> R.semester >> R.count; for(int i = 0; i < R.count; i++) input >> R.courses[i]; return input; } ostream & operator <<( ostream & os, const Registration & R ) { os << "Student ID: " << R.studentId << '\n' << "Semester: " << R.semester << '\n'; for(int i = 0; i < R.count; i++) os << R.courses[i] << '\n'; return os; }
// MAIN.CPP - Case Study, Student Registration // Chapter 3 example. #include <iostream.h> #include <fstream.h> #include "course.h" // Course class declaration #include "regist.h" // Registration class declaration // Main program: // Open an input file stream, read a Registration object, // including its list of courses. Redisplay all information, // and calculate the total credits taken. Write the results // to a file stream. int main() { ifstream infile( "rinput.txt" ); if( !infile ) return -1; Registration R; infile >> R; ofstream ofile( "routput.txt" ); ofile << R << "Number of courses = " << R.GetCount() << '\n' << "Total credits = " << R.GetCredits() << '\n'; // Declare and initialize a Course, and modify // its credits. Course aCourse( "MTH_3020", 'B', 2 ); aCourse.SetCredits( 5 ); cout << aCourse << endl; return 0; }