Use Definitions That Are Consistent with the Built-in Meaning

When you design a class, you should always think first about what operations the class will provide. Only after you know what operations are needed should you think about whether to define each operation as an ordinary function or as an overloaded operator. Those operations with a logical mapping to an operator are good candidates for defining as overloaded operators:

• If the class does IO, define the shift operators to be consistent with how IO is done for the built-in types.

• If the class has an operation to test for equality, define operator==. If the class has operator==, it should usually have operator!= as well.

• If the class has a single, natural ordering operation, define operator<. If the class has operator<, it should probably have all of the relational operators.

• The return type of an overloaded operator usually should be compatible with the return from the built-in version of the operator: The logical and relational operators should return bool, the arithmetic operators should return a value of the class type, and assignment and compound assignment should return a reference to the left-hand operand.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.144.194