【C++】运算符重载示例一
【摘要】 11.1、11.2
mytime0.h
//mytime0.h -- 时间类重载#ifndef MYTIME0_H_#define MYTIME0_H_ class Time{private: int hours; int minutes; public: Time(); Time(int h, int m = 0); void AddMin(int m); void ...
11.1、11.2
mytime0.h
-
//mytime0.h -- 时间类重载
-
#ifndef MYTIME0_H_
-
#define MYTIME0_H_
-
-
-
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 Sum(const Time & t) const;
-
void Show() const;
-
~Time();
-
};
-
-
#endif
-
mytime0.cpp
-
// mytime0.cpp -- 类的实现
-
#include<iostream>
-
#include "mytime0.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 %= 60;
-
}
-
-
void Time::AddHr(int h)
-
{
-
hours += h;
-
}
-
-
void Time::Reset(int h, int m)
-
{
-
hours = h;
-
minutes = m;
-
}
-
-
//参数设为引用是为了提高效率
-
//返回值不能是引用,否则由于是局部变量,一会就删除不存在了
-
//而Time在删除现在的sum之前会拷贝副本给调用的
-
Time Time::Sum(const Time & t) const
-
{
-
Time sum;
-
sum.minutes = minutes + t.minutes;
-
sum.hours = hours + t.hours + sum.minutes / 60;
-
sum.minutes %= 60;
-
return sum;
-
}
-
-
void Time::Show() const
-
{
-
std::cout << hours << "hours, " << minutes << " minutes";
-
}
-
-
-
-
-
Time::~Time()
-
{
-
}
usetime0.cpp
-
//usetime0.cpp -- 使用第一个版本的Time类
-
//记得和mytime0类编译
-
-
#include<iostream>
-
#include"mytime0.h"
-
-
int main()
-
{
-
using std::cout;
-
using std::endl;
-
Time planning;
-
Time coding(2, 40);
-
Time fixing(5, 55);
-
Time total;
-
-
cout << "计划时间是:";
-
planning.Show();
-
cout << endl;
-
-
cout << "代码实际时间是:";
-
coding.Show();
-
cout << endl;
-
-
cout << "调整时间是:";
-
fixing.Show();
-
cout << endl;
-
-
total = coding.Sum(fixing);
-
cout << "coding.Sum(fixing) = ";
-
total.Show();
-
cout << endl;
-
-
return 0;
-
}
运行结果
程序解读
其实我已经将重点的标注到程序里了,但是考虑大家未必认真看程序,还是说明有几个重要的地方要注意
文章来源: kings.blog.csdn.net,作者:人工智能博士,版权归原作者所有,如需转载,请联系作者。
原文链接:kings.blog.csdn.net/article/details/99291855
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)