C++运算符重载:operator

运算符重载:operator(翻译:操作)
    • 前置++
      • const Humanoperator ++() { ++i;  (*p)++;  return *this; }   //返回引用,防止值返回时的内存开销
      • 注意:++a;相当于a.operator++(),相当于调用函数,有返回值,也可以赋值
    • 后置++
      • const Human operator ++(int) { Human old(*this); i++; (*p)++; return old;}  //因为临时作用域结束的时候,就会释放,所以如果返回引用是空,所以返回值。
    • 加减+ / -
      • const Human operator +(const Human &r){return Human(i + r.geti(),*p+r.getp());}  //用const修饰形参,则需要r对象调用的函数要被const修饰,如:int get () const;
    • 赋值=
      • const Human &operator =(const Human &r) { if (this==&r) { return *this;} i = r.geti(); *p = r.getp();return *this; }  
      • 赋值运算符重载不用开辟空间,而复制构造函数可以当做构造函数使用,要开辟空间。
    • 转换类型运算符
      • operator int() { return i; }  //调用时  Human man;int x=int(man);或者int x=(man);或者int x=man;
    • 下标[]
      •     char &operator [](int index)
            {
                if (index >= 0 && index < length)
                {
                    return size[index];
                }
                else
                {
                    cout << "超出范围" << endl;
                    return size[length];
                }
            }  
      • 注意:
        • 由于函数的参数即是数组的下标,因此该函数只能带一个参数,不可带多个参数。
        • 由于下标运算符函数只限于本类的对象使用,因此不得将下标运算符函数重载为友元函数,且必须是非static类的成员函数。
    • <<:编译器判断<<左边是ostream的对象,就认为是输出;左边不是ostream的对象,就认为是位移操作符
      • 普通函数:ostreamoperator <<(ostream &outconst Human&man)
        {
            out << man.age << endl;
            out << man.heither << endl;
            return out;//由于cout是另一个类ostream的对象,ostream类没有公共的构造函数,
            //因此函数无法调用该类的复制构造函数,必须按引用的方法接受ostream的对象,并按引用的方式返回ostream对象
        }  
      • 友元函数:friend ostreamoperator <<(ostream &out, const Human&man)//因为该函数含有其他类的对象,所以这个函数就不能成为类Human的成员函数。加friend可以解决这个问题
            {
                out << man.age << endl;
                out << man.heither << endl;
                return out;
            }  
    • >>
      • friend istreamoperator >>(istream &in, Human&man)//因为该函数含有其他类的对象,所以这个函数就不能成为类Human的成员函数。加friend可以解决这个问题
            {
                in >> man.age;
                in >> man.heither;
                return in;
            }  
    • C++的运算符大部分可以被重载,但是有一些却不能重载。如“.”,"::","*","? :","#".
      • “.”,"::","*"在c++中有特殊的意义,假如重载的话会引起一些麻烦。
      • "#"是预处理标志,而不是运算符
      • "? :"没有确定性,重载没有意义
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值