以下两个代码段之间是否有任何功能差异?
bool ColorClass::setTo(int inRed, int inGreen, int inBlue)
{
amountRed = inRed;
amountGreen = inGreen;
amountBlue = inBlue;
return clipColor(amountRed, amountGreen, amountBlue);
}
bool ColorClass::setTo(int inRed, int inGreen, int inBlue)
{
amountRed = inRed;
amountGreen = inGreen;
amountBlue = inBlue;
if (clipColor(amountRed, amountGreen, amountBlue))
{
return true;
}
else
{
return false;
}
}
上面代码调用的函数定义如下:
bool ColorClass::clipColor(int &checkRed, int &checkGreen, int &checkBlue)
{
int numClips = 0; //numClips is used to counter number of clips made
checkColorBounds(checkRed, numClips);
checkColorBounds(checkGreen, numClips );
checkColorBounds(checkBlue, numClips);
return (numClips != 0);
}
void ColorClass::checkColorBounds(int &color, int &clipCounter)
{
if(color > MAXCOLOR)
{
color = MAXCOLOR;
clipCounter++;
}
else if (color < MINCOLOR)
{
color = MINCOLOR;
clipCounter ++;
}
}
我测试了两者并经历了两者,我似乎无法注意到任何功能上的不同。
我更喜欢第一个,因为它更有效,更有效(避免if-else)