(1)用户定义的转换的必要性:
我们希望能够在SmallInt对象和其他SmallInt对象或者内置算术类型的对象之间进行加减操作,我们要通过提供6个SmallInt操作符函数来实现对这些操作的支持:
class SmallInt ...{
friend operator+( const SmallInt &, int );
friend operator-( const SmallInt &, int );
friend operator-( int, const SmallInt & );
friend operator+( int, const SmallInt & );
public:
SmallInt( int ival ) : value( ival ) ...{ }
operator+( const SmallInt & );
operator- ( const SmallInt & );
// ...
private:
int value;
};
两个成员操作符允许我们加减两个SmallInt对象。友元全局操作符允许我们在SmallInt对象和内置算术类型的对象之间进行加减操作。之所以只需要6个操作符,是因为任何内置算术类型都可以被转换为与int型参数相匹配。
如果我们还想支持按位操作符、逻辑操作符、关系操作符和复合赋值操作符,则要求的操作符的数目就变得非常可怕了。我们更希望的,不是提供所有的重载操作符,而是一种将SmallInt类对象自动转换成int 型对象的方式。 !--判断阅读权限-->!--判断是否已经扣点--> |