operator op(aument-list)
如加号 operator +(aument-list)调用时则是调用这个函数。下面是对于C++Primer 的一个例子设计一个Time的类来进行时间的相加
class Time
{
private:
int m_hours;
int m_mins;
public:
void AddHour(int hour);
void AddMin(int minute);
void Reset(int hour,int min);
Time Sum(const Time& t) const;
Time();
void Show() const;
virtual ~Time();
};
{
private:
int m_hours;
int m_mins;
public:
void AddHour(int hour);
void AddMin(int minute);
void Reset(int hour,int min);
Time Sum(const Time& t) const;
Time();
void Show() const;
virtual ~Time();
};
实现
Time::Time()
{
m_hours=0;
m_mins=0;
}
Time::~Time()
{
}
void Time::AddHour(int hour)
{
m_hours+=hour;
}
void Time::AddMin(int minute)
{
m_mins+=minute;
m_hours+=m_mins/60;
m_mins%=60;
}
void Time::Reset(int hour,int min)
{
m_hours=hour;
m_mins=min;
}
Time Time::Sum(const Time& t) const
{
Time result;
result.m_hours=m_hours+t.m_hours;
result.m_mins=m_mins+t.m_mins;
result.m_hours+=result.m_mins/60;
result.m_mins%=60;
return result;
}
void Time::Show() const
{
std::cout << m_hours<<":" <<m_mins<<std::endl;
}
现在要实现+操作符重载由于功能和sum是一样的,所以只需要把sum的名字换成operator+就行了,其他完全不用改{
m_hours=0;
m_mins=0;
}
Time::~Time()
{
}
void Time::AddHour(int hour)
{
m_hours+=hour;
}
void Time::AddMin(int minute)
{
m_mins+=minute;
m_hours+=m_mins/60;
m_mins%=60;
}
void Time::Reset(int hour,int min)
{
m_hours=hour;
m_mins=min;
}
Time Time::Sum(const Time& t) const
{
Time result;
result.m_hours=m_hours+t.m_hours;
result.m_mins=m_mins+t.m_mins;
result.m_hours+=result.m_mins/60;
result.m_mins%=60;
return result;
}
void Time::Show() const
{
std::cout << m_hours<<":" <<m_mins<<std::endl;
}
Demo