+ -

C++重载操作符于转换 笔记

时间:2010-05-31

来源:woods2001

在手机上看
手机扫描阅读

重载操作符:
Overloaded functions that are members of a class may appear to have one less parameter than the number of operands. Operators that are member functions have an implicit this parameter that is bound to the first operand.
作为类成员的重载函数,其形参看起来比操作数数目少 1
。作为成员函数的操作符有一个隐含的 this 形参,限定为第一个操作数。

赋值(=)、下标([])、调用(())和成员访问箭头(->
)等操作符必须定义为成员,将这些操作符定义为非成员函数将在编译时标记为错误。

改变对象状态或与给定类型紧密联系的其他一些操作符,如自增、自减和解引用,通常就定义为类成类成员函数

对称的操作符,如算术操作符、相等操作符、关系操作符和位操作符,最好定义为普通非成员函数。

Ordinarily, a class that defines subscript needs to define two versions: one that is a nonconst member and returns a reference and one that is a const member and returns a const reference.
类定义下标操作符时,一般需要定义两个版本:一个为非 const
成员并返回引用,另一个为 const 成员并返回 const 引用。

定义自增/自减操作符
There is no language requirement that the increment or decrement operators be made members of the class. However, because these
operators change the state of the object on which they operate, our preference is to make them members.
C++ 语言不要求自增操作符或自减操作符一定作为类的成员,但是,因为这些操作符改变操作对象的状态,所以更倾向于将它们作为成员。

 标准库提供了一组函数适配器,用于特化和扩展一元和二元的函数对象,函数适配器分为一下两类:

binder 绑定器

它是一种函数适配器,他通过将一个操作数绑定而将二元函数转换成医院函数对象

Negator 求反器

求反器是一种函数适配器,他将谓词函数的真值求反.

转换操作符
是一种特殊的类成员函数。它定义将类类型值转变为其他类型值的转换。转换操作符在类定义体内声明,在保
糇 operator 之后跟着转换的目标类型:

class SmallInt

{
    public:
         SmallInt(int i = 0): val(i)
         { if (i < 0 || i > 255)
            throw std::out_of_range("Bad SmallInt initializer");
         }
         operator int() const { return val; }
    private:
         std::size_t val;

};

A conversion function must be a member function. The function may not specify a return type, and the parameter list must be empty.
转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空。

Only One Class-Type Conversion May Be Applied
只能应用一个类类型转换
        A class-type conversion may not be followed by another class-type
        conversion. If more than one class-type conversion is needed then the
        code is in error.
        类类型转换之后不能再跟另一个类类型转换。如果需要多个类类型转换,则代码将出错

类类型转换可能是实现和使用类的一个好处。通过为 SmallInt 定义到 int
 的转换,能够更容易实现和使用 SmallInt 类。int 转换使 SmallInt 的用户能够对 SmallInt
对象使用所有算术和关系操作符,而且,用户可以安全编写将 SmallInt
和其他算术类型混合使用的表达式。定义一个转换操作符就能代替定义 48
个(或更多)重载操作符,类实现者的工作就简单多了。

  下面留一个联系题:

  哪个 calc()
函数是如下函数调用的最佳可行函数?列出调用每个函数所需的转换序列,并解
释为什么所选定的就是最佳可行函数。
    class LongDouble {
    public
         LongDouble(double);
         // ...
    };
    void calc(int);
    void calc(LongDouble);
    double dval;
    calc(dval); // which function?
因为标准函数转换优于类类型转换

热门下载

更多