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(); 』 我現在正在喜歡重載的功能,但是要取捨其使用的時間,相信還有很大的進步空間。