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+定义为执行减法。比较常见但仍然不可取的是,扭曲运算子的通常意义来适应某个特定型别。运算子应该只用来表现用户必然能够明确理解的操作。意义不明确的运算子常被误以为有多种不同解释。
最佳练习:当一个重载运算子的意义不明确时,最好给这个操作一个名称(也就是改用成员函式)。通常,使用具名函式比勉强使用运算子表示一个少见的操作意义要好得多。如果某个操作比较特殊,没必要使用运算子来简短表示它。’
没有很懂纪录起来备查!
工作达人