函数的重构、代码优化例子

原来我是这么写 :
// override the operator
bool MyDate::operator== (const MyDate& ComparedDate) const
{
	bool isEqual = true;
	// year
	if (this->m_iYear != ComparedDate.m_iYear)
	{
		isEqual = false;
		return isEqual;
	}
	// month
	if (this->m_iMonth != ComparedDate.m_iMonth)
	{
		isEqual = false;
		return isEqual;
	}
	// day
	if (this->m_iDay != ComparedDate.m_iDay)
	{
		isEqual = false;
		return isEqual;
	}
	// hour
	if (this->m_iHour != ComparedDate.m_iHour)
	{
		isEqual = false;
		return isEqual;
	}
	// minute
	if (this->m_iMinute != ComparedDate.m_iMinute)
	{
		isEqual = false;
		return isEqual;
	}
	//second
	if (this->m_iSecond != ComparedDate.m_iSecond)
	{
		isEqual = false;
		return isEqual;
	}

	return isEqual;
}

 

后来 看到 答案后 改成:

bool Date::operator== (const MyDate& ComparedDate) const
{
	bool isEqual= (date.m_iYear == m_iYear
			&& date.m_iMonth == m_iMonth
			&& date.m_iDate == m_iDate
			&& date.m_iHour == m_iHour
			&& date.m_iMinute == m_iMinute
			&& date.m_iSecond == m_iSecond);
	return isEqual;
}

 

总结: 代码 简化了 很多, 而且 看起来比较舒服。

             可见 我原来的 代码 好冗余啊!

你可能感兴趣的:(优化,Date)