C++ examples for Class:Operator Overload
Using the Time class with an overloaded insertion operator.
#include <iostream> #include <iomanip> #include <iostream> class Time//from w ww . j a v a 2 s. c o m { 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; } }; std::ostream& operator <<(std::ostream& out, const Time& rT); // Overloaded insertion operator declaration // Constructor - implemented to allow specification of minutes and seconds more than 59 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; } int main() { Time period1(10,30,25); Time period2(1, 70,90); std::cout << "\nPeriod 1 is " << period1 << "\nPeriod 2 is " << period2 << std::endl; }