### 学习《C++ Primer》- 7

Part 7: 重载运算与类型转换(第14章)

// @author:       gr
// @date:         2015-01-08
// @email:        forgerui@gmail.com

一、重载运算符要求

定义一个运算符,它或者是类的成员,或者至少含有一个类类型的参数

二、重载输出运算符<<

operator<<一般要返回它的ostream的引用。

ostream &operator<< (ostream& os, const Sales_data& item){
    os << item.isbn() << " " << item.units_sold << " " << item.price();
    return os;
}

输入输出运算符必须是非成员函数:
因为这两个运算符的做操作数不可能是用户自定义类的对象,而是流类的对象cin、cout等。如果它需要使用类的私有成员变量,可以定义成友元函数。

三、相等运算符

相等运算符会比较对象的每一个数据成员,只有所有对应成员都相等,才认为相等。

四、下标运算符

下标运算符必须是成员函数。
下标运算符一般返回引用,同时定义常量和非常量版本。

五、递增运算符

前置运算符返回递增后的引用

StrBlobPtr& StrBlobPtr::operator++(){
    ++count;
    return *this;
}

后置运算符返回递增前的原值

StrBlobPtr StrBlobPtr::operator++(){
    //首先记录初值
    StrBlobPtr ret = *this;
    ++count;
    return ret;
}

六、函数调用运算符

定义了函数调用运算符就可以像函数一样使用对象

struct absInt{
    int operator(int val) const {
        return val < 0 ? -val : val;
    }
};

absInt test;
int res = test(-7);         //test是对象,而非函数

七、类型转换

class SmallInt{
    public:
        SmallInt(int i = 0):val(i){
            if (i < 0 || i > 255)
                throw std::out_of_range("Bad SmallInt value");
        }
        //将SmallInt转换为int
        operator int() const{
            return val;
        }
    private:
        std::size_t val;
};

SmallInt si = 4;
//转换为int
si + 3;
原文地址:https://www.cnblogs.com/gr-nick/p/4234718.html