原理链接:C++ 多态 重载 覆盖 2.1
1 函数重载
1.1头文件
#ifndef _TIME_
#define _TIME_
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m);
Time Add( Time &t1, Time &t2);
void show(const Time &t);
};
#endif
1.2 实现
#include "time.h"
#include <iostream>
using namespace std;
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
Time::Time()
{
hours = minutes = 0;
}
Time Time::Add(Time &t1, Time &t2)
{
Time toatal;
toatal.minutes = (t1.minutes + t2.minutes)%60;
toatal.hours = (t1.hours +t2.hours)+(t1.minutes + t2.minutes)/60;
return toatal;
}
void Time::show(const Time &t3)
{
cout<<"小时:"<<t3.hours<<endl;
cout<<"分钟::"<<t3.minutes<<endl;
}
1.3 main方法
#include "time.h"
#include <iostream>
using namespace std;
int main()
{
Time t1,t;
Time time1(3,3);
Time time2(5,90);
t = t1.Add(time1,time2);
t1.show(t);
system("pause");
return 0;
}
2 模板重载
2.1头文件
#ifndef _TIME_
#define _TIME
class Time
{
private:
int hourse;
int minutes;
public:
Time();
Time(int h, int m);
Time operator+(const Time &time);
Time operator-(const Time &time);
void show(const Time &time) const;
};
#endif
2.2方法实现
#include "time.h"
#include <iostream>
using namespace std;
Time::Time()
{
hourse = minutes =0;
}
Time::Time(int h, int m)
{
hourse = h;
minutes = m;
}
Time Time::operator+(const Time &time)
{
Time t;
t.hourse = (time.hourse+hourse)+(time.minutes+minutes)/60;
t.minutes = (minutes+time.minutes)%60;
return t;
}
Time Time::operator-(const Time &time)
{
Time sub;
Time sub1,sub2;
sub2.minutes = time.minutes+time.hourse*60;
/*cout<<"sub2.minutes"<<sub2.minutes<<endl;*/
sub1.minutes = minutes+hourse*60;
/*cout<<"sub2.minutes"<<sub1.minutes<<endl;*/
sub.minutes = (sub1.minutes-sub2.minutes)%60;
sub.hourse = (sub1.minutes-sub2.minutes)/60;
return sub;
}
void Time::show(const Time &tme) const
{
cout<<"小时:"<<tme.hourse<<"hours"<<endl;
cout<<"分钟:"<<tme.minutes<<"minutes"<<endl;
}
2.3main方法
#include "time.h"
#include <iostream>
using namespace std;
int main()
{
Time t1(4,35);
Time t2(2,80);
Time t,showt;
t= t1+t2;
showt.show(t);
t = t1-t2;
showt.show(t);
system("pause");
return 0;
}
注:以上代码都在VS2010 上可正常运行!