// Time class // Version 1.4 // // New in this version: operators. #include using std::ifstream; #include using std::cout; using std::cin; using std::istream; using std::ostream; class Time { public: friend istream & operator>>(istream & in, Time & t); Time() : Time(99, 99) {} Time(int h) : Time(h, 0) {} Time(int h, int m) : hours_(h), minutes_(m) {} // double operator-(const Time & t2) const; int hours() const { return hours_; } int minutes() const { return minutes_; } void set_hours(int new_hours) { hours_ = new_hours; } void set_minutes(int new_minutes) { minutes_ = new_minutes; } void set(int new_hours, int new_minutes = 0); private: int hours_; int minutes_; }; inline void Time::set(int new_hours, int new_minutes) { hours_ = new_hours; minutes_ = new_minutes; } //inline double Time::operator-(const Time & t2) const //{ // return (hours_ + minutes_/60.0) - // (t2.hours_ + t2.minutes_/60.0); //} inline double operator-( const Time & t1, const Time & t2 ) { return (t1.hours() + t1.minutes()/60.0) - (t2.hours() + t2.minutes()/60.0); } inline istream & operator>>(istream & in, Time & t) { // int new_hours; // in >> new_hours; // t.set_hours(new_hours); in >> t.hours_; in.get(); // colon in >> t.minutes_; return in; } inline ostream & operator<<(ostream & out, const Time & t) { out << t.hours() << ':'; if ( t.minutes() < 10 ) out << '0'; out << t.minutes(); return out; } int main() { cout << "Testing subtraction operator...\n"; Time t1(8,30), t2(6,15); cout << t1 - t2 << '\n'; cout << t2 - 6 << '\n'; cout << 7 - t2 << '\n'; cout << "\nTesting input and output operators...\n"; ifstream f("times.txt"); Time t; while (f >> t) cout << t << '\n'; cout << "\nTesting chains of input and output operators...\n" << "Enter two times: "; cin >> t1 >> t2; cout << t1 << ' ' << t2 << '\n'; return 0; }