C++ 运算符重载

来源:互联网 发布:金融大数据应该学什么 编辑:程序博客网 时间:2024/05/24 06:32
  • 运算符重载的方法:函数类型 operator 运算符名词 (形参表列)
    • 如Complex operator + (Complex &c1) {... return c3;}
    • c3 = c1 + c2;     // c++系统解释为c1.operator+(c2),"operator +" 是Complex的一个成员函数

  • 运算符重载规则:
    •   (1) 只能对已有的C++运算符进行重载,除了.,.*,::,sizeof,?:
    •   (2) 重载不能改变运算符运算的个数
    •   (3) 重载不能改变运算符的优先级
    •   (4) 重载不能改变运算符的结合性
    •   (5) 重载不能有默认的参数
    •   (6) 重载运算符必须和用户自定义类型的对象一起使用,不能全是C++标准类型
    •   (7) 运算符"="和"&"不必重载
    •   (8) 重载的运算符的功能类型应该该类似运算之前的功能
    •   (9) 运算符重载函数可以是类的成员函数或者友元函数,或者普通函数。

  • 运算符重载作为类成员函数和友元函数  
    •   (1) Complex operator + (Complex &c2)    // Complex的成员函数,调用默认的this指针
    •   (2) friend Complex operator + (Complex &c1, Complex &c2)
    •   (3) friend Complex operator + (int &i, Complex &c)    // c2 = i + c1
    •   (4) friend Complex operator + (Complex &c, int &i)    // c2 = c1 + i

  • 重载双目运算符
  •   friend bool operator > (String &string1, String &string2)

  • 重载单目运算符
  •   (1) Time operator ++ ();         // 重载前置自增运算符, i++
  •   (2) Time operator ++ (int);    // 重载后置自增运算符, ++i

  • 重载流插入运算符和流提取运算符
  •   (1) 重载流插入运算符"<<":friend ostream& operator << (ostream &output, Complex &c)  {... return output;}
  •   (2) 重载流提取运算符">>":friend istream& operator >> (istream &input, Complex &c)  {... return input;}

  • 标准类型数据间的转换
  •   (1) 隐式转换:int i = 7.5;
  •   (2) 显示转换:类型名(数据)或者(类型名)数据

  • 用构造函数进行类型转换:Complex(double r) {real = r; imag = 0;}// complex + double,转换double为Complex数据类型
  • 用类型转换函数进行类型转换:operator 类型名() {实现转换的语句}    // operator double() {return real;}