大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←
问题:
解答:
main.cpp
#include "mytime3.h"
#include <iostream>
using namespace std;
int main()
{
Time aida(3, 35);
Time tosca(2,48);
Time temp;
cout << "Aida and Tosca:\n";
cout << aida << "; " << tosca << endl;
temp = aida + tosca;
cout << "Aida+Tosca: " << temp << endl;
temp = aida * 1.17;
cout << "Aida*1.17: "<<temp << endl;
cout << "10.0 * Tosca: " << 10.0 * tosca << endl;
return 0;
}
mytime3.h
#pragma once
#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 n)const;*/
friend Time operator+(const Time& t1, const Time& t2);
friend Time operator-(const Time& t1, const Time& t2);
friend Time operator*(const Time& t1, double n);
friend Time operator*(double m, const Time& t) { return t * m; }
friend ostream& operator<<(ostream& os, const Time& t);
};
mytime3.cpp
#include "mytime3.h"
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
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::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 tot1, tot2;
// tot1 = t.minutes + 60 * t.hours;
// tot2 = minutes + 60 * hours;
// diff.minutes = (tot2 - tot1) % 60;
// diff.hours = (tot2 - tot1) / 60;
// return diff;
//}
//Time Time::operator*(double n)const
//{
// Time result;
// long totalminutes = hours * n * 60 + minutes * n;
// result.hours = totalminutes / 60;
// result.minutes = totalminutes % 60;
// return result;
//}
Time operator+(const Time& t1, const Time& t2)
{
Time sum;
sum.minutes = t1.minutes + t2.minutes;
sum.hours = t1.hours + t2.hours + sum.minutes / 60;
sum.minutes = sum.minutes % 60;
return sum;
}
Time operator-(const Time& t1, const Time& t2)
{
Time diff;
int tot1, tot2;
tot1 = t2.hours * 60 + t2.minutes;
tot2 = t1.hours * 60 + t1.minutes;
diff.minutes = (tot2 - tot1)%60;
diff.hours = (tot2 - tot1) / 60;
return diff;
}
Time operator*(const Time& t1, double n)
{
Time res;
long totalminutes = t1.hours * n * 60 + t1.minutes * n;
res.hours = totalminutes / 60;
res.minutes = totalminutes % 60;
return res;
}
ostream& operator<<(ostream& os, const Time& t)
{
os << t.hours << " hours, " << t.minutes << " minutes";
return os;
}
运行结果:
考查点:
- 运算符重载
- 友元
- 时间相加减
2024年9月5日16:56:56