11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

352Part V: Optional FeaturesI would like to implement maximum() for all four cases. Of course, C++ can promoteall of the types specified into double. Thus, you could argue that themaximum(double, double) version is all that is actually needed. Consider,however, what that would mean to the following expression:// prototype a max() functiondouble maximum(double, double);// user functionvoid fn(int nArg1, int nArg2){int nLarger = (int)maximum((double)nArg1, (double)nArg2);}// ...continue...In this case, both nArg1 and nArg2 must be promoted to double with theaccompanying loss of accuracy. This maximum() function returns a double.This value must be demoted from double back to an int via the cast beforeit can be assigned to nLarger. The function might work without loss of accuracy,but the numerous conversions take much more computer time than asilly maximum() function should. In any case, the function doesn’t work theway the user would expect or hope.Of course, you could overload maximum() with all the possible versions:double maximum(double d1, double d2){if (d1 > d2){return d1;}return d2;}int maximum(int n1, int n2){if (n1 > n2){return n1;}return n2;}char maximum(char c1, char c2){if (c1 > c2){return c1;}return c2;}// ...repeat for all other numeric types...

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!