Conversions and Operators

C++ Primer 4/e在Conversions and Class Types這個地方有一個警告:『Correctly designing the overloaded operators, conversion constructors, and conversion functions for a class requires some care. In particular, ambiguities are easy to generate if a class defines both conversion operators and overloaded operators. A few rules of thumb can be helpful:

  1. Never define mutually converting classesthat is, if class Foo has a constructor that takes an object of class Bar, do not give class Bar a conversion operator to type Foo.

  2. Avoid conversions to the built-in arithmetic types. In particular, if you do define a conversion to an arithmetic type, then

    • Do not define overloaded versions of the operators that take arithmetic types. If users need to use these operators, the conversion operation will convert objects of your type, and then the built-in operators can be used.

    • Do not define a conversion to more than one arithmetic type. Let the standard conversions provide conversions to the other arithmetic types.

The easiest rule of all: Avoid defining conversion functions and limit nonexplicit constructors to those that are “obviously right.”』

中文版的這樣寫:『你必須很謹慎,才能正確設計出重載運算子、轉換建構式和class轉換函式。尤其如果class定義了轉換運算子和重載運算子,很容易就產生歧義。下面這些經驗法則或許可以帶給你幫助:

  1. 不要定義相互轉換的classes。也就是說如果class Foo有個建構式帶一個class Bar物件為參數,那就不要為class Bar定義一個轉至Foo的轉換運算子。
  2. 避免轉換至內建算術型別。更明確地說,如果你為class定義了一個算術型別轉換,那麼:
  • 不要重載「帶有算術型別」的運算子。萬一用戶使用這些運算子,轉換操作會先將你的物件轉換,然後內建的運算子才能被用上。
  • 不要定義「能使class轉至一個以上的算術型別」的轉換操作(s)。讓標準轉換負責「轉至其他算術型別」。

最簡單的規則是:面對「明顯正確」的形式,避免為它們定義轉換函式,並有限度地使用non-explicit建構式。』

純紀錄!

Print Friendly, PDF & Email

發佈留言

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

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