OOP笔记:操作符过载

  • 3种实现方式:成员函数友员函数普通函数
    class Employee
    {
      protected:
        // …
      public:
        // …
        Employee & operator ++()
          { Age ++; return *this; }

        friend Employee & operator --( Employee & e)
          { e.Age --; return e; }

        // …
    };
    bool operator== (Employee, Employee);

  • 2种调用方式:在表达式中引用操作符函数调用
    class complex {
        double re, im;
      public:
        complex(double r, double i)
        { re=r; im=i; }
        complex operator+ (complex c);
        complex operator* (complex c);
    };
    bool operator== (complex, complex);

    void f()
    {
      complex a = complex(1, 3.1);
      complex b(1.2, 2);
      complex c = b;
      a = b + c;
      a = b.operator+(c);
      bool e = a == b;
      e = operator==(a, b);
    }

  • For any prefix unary operator @, @aa can be interpreted as either aa.operator@( ) or operator@(aa). For any postfix unary operator @, aa@ can be interpreted as either aa.operator@(int) or operator@(aa, int)(这里的int 是后缀一元操作符的标志参数)。

  • C++的一些限制:
    • 过载定义操作符=、[ ]、( )、->的必须是非静态成员函数,以保证其第一操作数一定是左值(lvalue );
    • 不允许在过载定义操作符时使得所有操作数都是基本类型的,这也就是说,过载定义操作符时至少有一个操作数是自定义类型的;
    • 欲使第一操作数为基本类型者,不能定义为成员函数。 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值