C++ examples for Class:Operator Overload
Using the Time class with an overloaded extraction operator implemented as a friend of the Time class
#include <iostream> #include <iomanip> class Time//from ww w .j a va 2 s . com { private: int hours {}; int minutes {}; int seconds {}; public: Time() = default; Time(int h, int m, int s); int getHours()const { return hours; } int getMinutes()const { return minutes; } int getSeconds()const { return seconds; } friend std::istream& operator>> (std::istream& in, Time& rT); // Friend extraction operator }; std::ostream& operator <<(std::ostream& out, const Time& rT); // Overloaded insertion operator declaration // Constructor Time::Time(int h, int m, int s) { seconds = s%60; // Seconds left after removing minutes minutes = m + s/60; // Minutes plus minutes from seconds hours = h + minutes/60; // Hours plus hours from minutes minutes %= 60; // Minutes left after removing hours } // Insertion operator std::ostream& operator <<(std::ostream& out, const Time& rT) { out << ' ' << rT.getHours() << ':'; char fillCh {out.fill('0')}; // Set fill for leading zeros out << std::setw(2) << rT.getMinutes() << ':' << std::setw(2) << rT.getSeconds() << ' '; out.fill(fillCh); // Restore old fill character return out; } // Extraction operator std::istream& operator>> (std::istream& in, Time& rT) { char ch {}; // Stores ':' in >> rT.hours >> ch >> rT.minutes >> ch >> rT.seconds; // Ensure seconds and minutes less than 60 rT.minutes += rT.seconds/60; rT.hours += rT.minutes/60; rT.minutes %= 60; rT.seconds %= 60; return in; } int main() { Time period1; Time period2; std::cout << "\nEnter a time as hours:minutes:seconds, and press Enter: "; std::cin >> period1; std::cout << "\nEnter another time as hours:minutes:seconds, and press Enter: "; std::cin >> period2; std::cout << "\nPeriod 1 is " << period1 << "\nPeriod 2 is " << period2 << std::endl; }