Use Operator Overloading Judiciously

C++ Primer 4/e在Defining an Overloaded Operator這個地方有一個警告:『Each operator has an associated meaning from its use on the built-in types. Binary +, for example, is strongly identified with addition. Mapping binary + to an analogous operation for a class type can provide a convenient notational shorthand. For example, the library string type, following a convention common to many programming languages, uses + to represent concatenation”adding” one string to the other.

Operator overloading is most useful when there is a logical mapping of a built-in operator to an operation on our type. Using overloaded operators rather than inventing named operations can make our programs more natural and intuitive. Overuse or outright abuse of operator overloading can make our classes incomprehensible.

Obvious abuses of operator overloading rarely happen in practice. As an example, no responsible programmer would define operator+ to perform subtraction. More common, but still inadvisable, are uses that contort an operator’s “normal” meaning to force a fit to a given type. Operators should be used only for operations that are likely to be unambiguous to users. An operator with ambiguous meaning, in this sense, is one that supports equally well a number of different interpretations.

最佳練習:When the meaning of an overloaded operator is not obvious, it is better to give the operation a name. It is also usually better to use a named function rather than an operator for operations that are rarely done. If the operation is unusual, the brevity of using an operator is unnecessary.』

中文版的這樣寫:『每個運算子都有其相應於built-in types的相關意義。例如二元的+運算子總是被視為加法,因此把這個運算子施行於class type可以讓讀者從符號上就輕易理解操作意義。例如標準庫的string型別遵循了被很多編程語言奉行的約定,以+代表串接動作,把某個字串加至另一個字串。

當內建運算子和我們的classes操作有邏輯映射關係時,運算子重載就很有用。以重載運算子取代具名函式,可使程式更自然更直觀。過度使用或甚至濫用運算子,則會使classes難以理解。

現實中明顯濫用運算子重載的情況很少發生。例如,任何負責任的程式員都不可能將operator+定義為執行減法。比較常見但仍然不可取的是,扭曲運算子的通常意義來適應某個特定型別。運算子應該只用來表現用戶必然能夠明確理解的操作。意義不明確的運算子常被誤以為有多種不同解釋。

最佳練習:當一個重載運算子的意義不明確時,最好給這個操作一個名稱(也就是改用成員函式)。通常,使用具名函式比勉強使用運算子表示一個少見的操作意義要好得多。如果某個操作比較特殊,沒必要使用運算子來簡短表示它。』

沒有很懂紀錄起來備查!

工作達人

Print Friendly, PDF & Email

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料