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 );
  • 不允许在过载定义操作符时使得所有操作数都是基本类型的,这也就是说,过载定义操作符时至少有一个操作数是自定义类型的;
  • 欲使第一操作数为基本类型者,不能定义为成员函数。 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章