昨天的問題,實現一個簡單的時鐘類,包含小時和分鐘,方法有顯示和相加。
0.cpp
#include <iostream>
using namespace std;
///define class Clock
class Clock
{
public:
Clock(int, int);
void showTime();
Clock& add(Clock& c1, Clock& c2);
int hour;
int minutes;
};
///ctor
Clock::Clock(int h, int m)
{
hour = h;
minutes = m;
}
void Clock::showTime()
{
cout<<"The time is:"<<hour<<"h"<<minutes<<"m"<<endl;
}
Clock& add(Clock& c1, Clock& c2)
{
c1.hour += c2.hour;
c1.minutes += c2.minutes;
return c1;
}
int main()
{
cout<<"Please enter two integers:";
int h, m;
cin>>h>>m;
Clock clock1(h, m);
clock1.showTime();
cout<<"Please enter two integers:";
cin>>h>>m;
Clock clock2(h, m);
clock2.showTime();
cout<<"Add the two Clock object:";
clock1 = add(clock1, clock2);
clock1.showTime();
return 0;
}
結果為:
上面的代碼很簡陋,今天的目標是改進它。主要有幾點:
1.類裏成員訪問限制改為public。
2.檢查小時和分鐘的範圍,更加合理。
3.使用函數操作符重載,如+ -。
Tags:
include minutes public return
文章來源: