Team LiB
Previous Section Next Section

Chapter Summary

小结

Chapter 5 described the rich set of operators that C++ defines for the built-in types. That chapter also covered the standard conversions, which automatically convert operands from one type to another.

第五章介绍了 C++ 为内置类型所定义的丰富的操作符集合,该章也涵盖了标准转换,标准转换自动将操作数从一个类型转换为另一类型。

We can define a similarly rich set of expressions for objects of our own types (i.e., class or enumeration types) by defining overloaded versions of the built-in operators. An overloaded operator must have at least one operand of class or enumeration type. An overloaded operator has the same number of operands, associativity, and precedence as the corresponding operator when applied to the built-in types.

通过定义内置操作符的重载版本,我们可以为自己的类型(即,类类型或枚举类型)的对象定义同样丰富的表达式集合。重载操作符必须具有至少一个类类型或枚举类型的操作符。应用于内置类型时,重载操作符与对应操作符具有同样数目的操作数、同样的结合性和优先级。

Most overloaded operators can be defined as class members or as ordinary non-member functions. The assignment, subscript, call, and arrow operators must be class members. When an operator is defined as a member, it is a normal member function. In particular, member operators have an implicit this pointer, which is bound to the first (only operand for unary operators, left-hand operand for binary operators) operand.

大多数重载操作符可以定义为类成员或普通非成员函数,赋值操作符、下标操作符、调用操作符和箭头操作符必须为类成员。操作符定义为成员时,它是普通成员函数。具体而言,成员操作符有一个隐式 this 指针,该指针一定是第一个操作数,即,一元操作符唯一的操作数,二元操作符的左操作数。

Objects of classes that overload operator(), the function call operator, are known as "function objects." Such objects are often used to define predicate functions to be used in combination with the standard algorithms.

重载了 operator()(即,函数调用操作符)的类的对象,称为“函数对象”。这种对象通常用于定义与标准算法结合使用的谓词函数。

Classes can define conversions that will be applied automatically when an object of one type is used where an object of a different type is needed. Constructors that take a single parameter and are not designated as explicit (Section 12.4.4, p. 462) define conversions from the class type to other types. Overloaded operator conversion functions define conversions from other types to the class type. Conversion operators must be members of the class that they convert. They have no parameters and define no return value. Conversion operators return a value of the type of the operatorfor example, operator int returns an int.

类可以定义转换,当一个类型的对象用在需要另一不同类型对象的地方时,自动应用这些转换。接受单个形参且未指定为 explicit第 12.4.4 节)的构造函数定义了从其他类型到类类型的转换,重载操作符转换函数则定义了从类类型到其他类型的转换。转换操作符必须为所转换类的成员,没有形参并且不定义返回值,转换操作符返回操作符所具有类型的值,例如,operator int 返回 int

Both overloaded operators and class-type conversions can make types easier and more natural to use. However, care should be taken to avoid designing operators or conversions that are not obvious to users of the type and to avoid defining multiple conversions between one type and another.

重载操作符和类类型转换都有地更容易、更自然地使用类型,但是,必须注意避免设计对用户而言不明显的操作符和转换,而且应避免定义一个类型与另一类型之间的多个转换。

Team LiB
Previous Section Next Section