本文主要是介绍C++PrimerPlus(第六版)中文版:第十一章使用类-计算时间:一个运算符重载示例(+,-,* 全部的运算符重载),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
mytime2.h 内容如下:
#pragma once
#ifndef MYTIME1_H_
#define MYTIME1_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 operator+(const Time& t)const;Time operator-(const Time& t)const;Time operator*(double n)const;//Time Sum(const Time& t) const;void Show() const;
};
#endif // !MYTIME0_H_#pragma once
mytime2.cpp 文件内容如下:
#include <iostream>
#include "mytime2.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 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 mult) const {Time result;long totalminutes = hours * mult * 60 + minutes * mult;result.hours = totalminutes / 60;result.minutes = totalminutes % 60; return result;}void Time::Show()const
{std::cout << hours << "hours," << minutes << "minutes";
}
usetime2.cpp 文件内容如下:
#include <iostream>
#include "mytime2.h"int main()
{std::cout << "Hello World!\n";using std::cout;using std::endl;Time planning;Time weeding(4, 35);Time waxing(2, 47);Time total;Time diff;Time adjusted;cout << "weeding time=";weeding.Show();cout << endl;cout << "waxing time=";waxing.Show();cout << endl;cout << "total working time=";total = weeding + waxing;//use operator +total.Show();cout << endl;diff = weeding - waxing; //use operator - cout << "weeding time - waxing time=";diff.Show();cout << endl;adjusted = total * 1.5; //use operator*cout << "adjusted work time =";adjusted.Show();cout << endl;return 0;}// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
这篇关于C++PrimerPlus(第六版)中文版:第十一章使用类-计算时间:一个运算符重载示例(+,-,* 全部的运算符重载)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!