类的使用
//运算符重载operator+()等 #ifndef MYTIME_H_ #define MYTIME_H_ class Time { public: Time(); Time(int h, int m = 0); void AddMin(int m); void AddHr(int n); void Reset(int h = 0, int n = 0); //如果想进行“+”的重载,只需要将sum换成operator+(),重载不能违反其他操作符的使用,使用时可以使用函数也可以直接使用“+” Time sum(const Time& t) const; Time operator+(const Time& t) const; Time operator-(const Time& t) const; Time operator*(double n) const; void Show() const; ~Time(); /*C++除了使用公有函数访问私有成员外还可以用友元,友元包括友元函数、友元类、友元成员函数,通过让函数成为类的友元即可访问 友元函数的声明在函数声明中,加上关键字friend*/ friend Time operator*(double m, const Time& t) { return t * m; } friend std::ostream& operator<<(std::ostream & os, const Time& t); private: int hours; int minutes; }; #endif // !MYTIME_H_
#include <iostream> #include "mytime.h" Time::Time() { hours = minutes = 0; } Time::Time(int h, int m) { hours = h; minutes = m; } Time::~Time() { } void Time::AddMin(int m) { minutes += m; hours += minutes / 60; minutes = minutes % 60; } void Time::AddHr(int h) { hours += h; } void Time::Reset(int h, int m) { hours = h; minutes = m; } Time Time::sum(const Time& t) const { Time sum; sum.minutes = minutes + t.minutes; sum.hours = hours + t.hours + sum.minutes / 60; sum.minutes = sum.minutes % 60; return sum; } Time Time::operator+(const Time& t) const { Time sum; sum.minutes = minutes + t.minutes; sum.hours = hours + t.hours + sum.minutes / 60; sum.minutes = sum.minutes % 60; return sum; } Time Time::operator-(const Time& t) const { Time diff; int tol1, tol2; tol1 = t.minutes + 60 * t.hours; tol2 = minutes + 60 * hours; diff.minutes = (tol2 - tol1) % 60; diff.hours = (tol2 - tol1) / 60; return diff; } Time Time::operator*(double mult) const { Time result; long totalminutes = hours * mult * 60 + minutes * mult; result.hours = totalminutes / 60; result.minutes = totalminutes % 60; return result; } std::ostream& operator<<(std::ostream& os, const Time& t) { os << t.hours << " hours," << t.minutes << " minnutes"; return os; } void Time::Show() const { std::cout << hours << " hours," << minutes << " minutes" << std::endl; }