C++ Primer 4/e 在Overloaded Functions这里还有一个忠告:‘Although overloading can be useful in avoiding the necessity to invent (and remember) names for common operations, it is easy to take this advantage too far. There are some cases where providing different function names adds information that makes the program easier to understand. Consider a set of member functions for a Screen class that move Screen‘s cursor.
Screen& moveHome(); Screen& moveAbs(int, int); Screen& moveRel(int, int, char *direction);
It might at first seem better to overload this set of functions under the name move:
Screen& move(); Screen& move(int, int); Screen& move(int, int, *direction);
However, by overloading these functions we’ve lost information that was inherent in the function names and by doing so may have rendered the program more obscure.
Although cursor movement is a general operation shared by all these functions, the specific nature of that movement is unique to each of these functions. moveHome, for example, represents a special instance of cursor movement. Which of the two calls is easier to understand for a reader of the program? Which of the two calls is easier to remember for a programmer using the Screen class?
// which is easier to understand? myScreen.home(); // we think this one! myScreen.move(); ’ 中文版的是这样说:‘虽然重载或许可以免除程式具有共通操作(common operation)构思并记忆各式各样的名称,但这个优点很容易被滥用。某些状况下提供不同的函式名称能增加资讯量,使程式更容易被了解。考虑Screen class的一组成员函式,用以移动Screen的游标: Screen& moveHome(); Screen& moveAbs(int, int); Screen& moveRel(int, int, char *direction); 乍看之下将这组函式以move为名加以重载会好一些: Screen& move(); Screen& move(int, int); Screen& move(int, int, *direction); 然而重载之后我们损失了函式名称所蕴含的资讯,使程式变得比较晦涩难懂。 虽然“移动游标”是这些函式共有的一般操作,但每个函式的移动都有其独特本质。例如moveHome是移动游标的一个特殊案例。对程式阅读者而言,下面两个呼叫那一个比较容易理解?对使用Screen的程式员而言,哪一个比较容易记住? //以下哪一个比较容易了解? myScreen.home(); // 我们认为是这个! myScreen.move(); ’ 我现在正在喜欢重载的功能,但是要取舍其使用的时间,相信还有很大的进步空间。