# 运算符重载基础

"<<"是C++中的左移运算符，但是在输出操作中与cout配合被称为流插入运算符，可以进行输出。
">>"是右移运算符，与cin配合使用被称为流提取运算符。

CTime重载+运算符实现两个CTime对象的相加，
time1 + time2

```CTime operator+(CTime& time1, CTime& time2)
```

```CTime operator+(CTime& time)
```

Time.h中声明友元函数

```friend CTime addTime(CTime& time1, CTime& time2);
```

main.cpp中直接实现

```CTime addTime(CTime& time1, CTime& time2)//这里的相加是时分秒进行相加，满60进1
{
int hour=0, minute = 0;
int second = time1.m_nSecond + time2.m_nSecond;
if (second > 60)
{
minute++;
second -= 60;
}

minute += (time1.m_nMinute + time2.m_nMinute);
if (minute > 60)
{
hour++;
minute -= 60;
}

hour += (time1.m_nHour + time2.m_nHour);
if (hour > 24)
{
hour -= 24;
}
return CTime(hour,minute,second);
}

//输出
int main()
{
CTime time(10, 50, 20);
CTime time2(12);
std::cout << time3.getHour() << ":" << time3.getMinute() << ":" << time3.getSecond() << endl;
getchar();
return 0;
}
```

+号运算重载：

Time.h中声明

```friend CTime operator+(CTime& time1, CTime& time2);
```

main.cpp中实现

```CTime operator+(CTime& time1, CTime& time2)
{
int hour = 0, minute = 0;
int second = time1.m_nSecond + time2.m_nSecond;
if (second > 60)
{
minute++;
second -= 60;
}

minute += (time1.m_nMinute + time2.m_nMinute);
if (minute > 60)
{
hour++;
minute -= 60;
}

hour += (time1.m_nHour + time2.m_nHour);
if (hour > 24)
{
hour -= 24;
}
return CTime(hour, minute, second);
}

int main()
{
CTime time(10, 50, 20);
CTime time2(12);

CTime time4 = time + time2; //使用+号重载对两个CTime对象进行相加
std::cout << time4.getHour() << ":" << time4.getMinute() << ":" << time4.getSecond() << endl;

getchar();
return 0;
}
```

## 输出结果:

Time.h中声明

```CTime operator+(CTime& time);
```

Time.cpp中实现

```CTime CTime::operator+(CTime& time)
{
int hour = 0, minute = 0;
int second = this->m_nSecond + time.m_nSecond;
if (second > 60)
{
minute++;
second -= 60;
}

minute += (this->m_nMinute + time.m_nMinute);
if (minute > 60)
{
hour++;
minute -= 60;
}

hour += (this->m_nHour + time.m_nHour);
if (hour > 24)
{
hour -= 24;
}
return CTime(hour, minute, second);
}
```

main.cpp中调用

```int main()
{
CTime time(10, 50, 20);
CTime time2(12);
CTime time4 = time.operator+(time2);
std::cout << time4.getHour() << ":" << time4.getMinute() << ":" << time4.getSecond() << endl;

getchar();
return 0;
}
```

# 源代码下载地址：

GITHUB源码下载地址:点我进行下载

anyShare分享到：