Xin lỗi, bây giờ đọc lại thấy mình diễn đạt tViet tệ qua'! (dúng là dầu chuột). 'Dauchuot' đưa code chạy được ra nè:
===============================
(mytime3.h)
Code:
#ifndef MYTIME3_H_
#define MYTIME3_H_
#include <iostream>
using namespace std;
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = 0);
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0, int m = 0);
Time operator+(const Time & t) const;
Time operator-(const Time & t) const;
Time operator*(double mult) const;
friend Time operator*(double m, const Time & t)
{ return t * m;}
friend ostream & operator<<(ostream & os, const Time & t);
};
#endif
==================================
(mytime3.cpp)
Code:
#include "mytime3.h"
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
void Time::AddHr(int h)
{
hours += h;
}
void Time::AddMin(int m)
{
minutes += m;
hours += minutes / 60;
minutes %= 60;
}
void Time::Reset(int h, int m)
{
hours = h;
minutes = m;
}
Time Time::operator +(const Time & t) const
{
Time sum;
sum.minutes = minutes + t.minutes;
sum.hours = hours + t.hours + sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
Time Time::operator -(const Time & t) const
{
Time diff;
int mot1, mot2;
mot1 = t.minutes + t.hours * 60;
mot2 = minutes + hours * 60;
diff.minutes = (mot1 - mot2) / 60;
diff.hours = (mot1 - mot2) % 60;
return diff;
}
Time Time::operator*(double mult) const
{
Time result;
long totalmin = (hours * 60 + minutes) * mult;
result.hours = totalmin / 60;
result.minutes = totalmin % 60;
return result;
}
ostream & operator<<(ostream & os, const Time & t)
{
os << t.hours << " hours, " << t.minutes << " minutes";
return os;
}
=======================
(usemytime3.ccp)
Code:
#include <iostream>
using namespace std;
#include "mytime3.h"
int main()
{
Time A;
Time B(5, 40);
Time C(2, 55);
cout << "A, B, C:\n";
cout << A << "; " << B << "; " << C << endl;
A = B + C;
cout << "B + C: " << A << endl;
A = B * 2;
cout << "B * 2: " << A << endl;
cout << "10 * B: " << 10 * B << endl;
return 0;
}
=================================
(B * 2.75 chạy được tất nhiên B * 2 phải chạy chứ, copy code kiểm tra lại thử cho trường hợp 2.75 và 2 thử xem)
Câu hỏi: ở header file có khai báo
friend Time operator*(double m, const Time & t)
{ return t * m;}
chường trình Build Solution( nhấn F7) được. Nếu bỏ đi từ khóa friend tức là chỉ khai báo trong mytime3.h như sau:
Time operator*(double m, const Time & t)
{ return t * m;}
---> Không Build được. 'Dauchuot' kg hiểu tại sao bỏ friend đi thì không build được, thây có dính dang gì tới t.minutes, t.hours đâu.