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建构式。’

纯纪录!