操作符重载(day07)

二十 操作符重载
eg:复数x+yi 3+4i
(1+2i) + (3+4i) = 4+6i
1 双目操作符(L # R)
1.1 运算类的双目操作符:+ - * /
-->左右操作数可以是左值也可以是右值
-->表达式结果是右值
1)成员函数形式
L#R的表达式会被编译器自动处理为L.operator#(R)的成员函数调用,该函数的返回值即为表达式的值。

2)全局函数形式 
L#R的表达式会被编译器自动处理为operator#(L,R)的全局函数调用,该函数的返回值即为表达式的值。

注:通过friend关键字,可以把一个全局函数声明为某个类的友元,友元函数可以访问类中的任何成员。

1.2 赋值类的双目操作符
-->左操作数是左值(不能是常量),右操作数可以是左值也可以是右值
-->表达式结果是左值,就是左操作的自身
1)成员函数形式:
   L # R --》L.operator#(R);
2)全局函数形式:
   L # R --》operator#(L,R);
--------------------
2 单目操作符重载 #O
2.1 计算类单目操作符:-(取负) ~ !
-->操作数可以左值也可以值右值
-->表达式结果是一个右值
1)成员函数形式
   #O --》O.operator#();   
2)全局函数形式
   #O --》operator#(O);

2.2 自增减单目操作符: ++/--
1)前缀自增减
--》操作数是左值
--》表达式结果就是操作数自身,也是左值
成员函数形式:
  #O--> O.operator#()
全局函数形式:
  #O--> operator#(O)

2)后缀自增减
--》操作数是左值
--》表达式结果是自增减之前的副本(右值)
成员函数形式:
  O#--> O.operator#(int/*哑元*/)
全局函数形式:
  O#--> operator#(O,int/*哑元*/)

---------------------------
3 插入和提取操作符: << >>
功能:实现自定义类型的输入和输出的功能
注:只能用全局函数形式
#include <iostream>
ostream cout;
istream cin;
cout << a;//operator<<(cout,a);
friend ostream& operator<<(
        ostream& os,const RIGHT& right){...}

cin >> a;//operator>>(cin,a);
friend istream& operator>>(
        istream& is,RIGHT& right);
==========================================
练习:实现3x3矩阵类,支持如下操作符重载
<< + - += -= -(取负) ++(前后) --(前后) 
要求:除了<<,都使用成员函数形式
class M33{
public:
   M33(void){
         for(int i=0;i<3;i++)
            for(int j=0;j<3;j++)
                m_a[i][j] = 0; 
   }
   M33(int a[][3]){
         for(int i=0;i<3;i++)
            for(int j=0;j<3;j++)
                m_a[i][j] = a[i][j];        
   }
   const M33 operator+(const M33& m)const{
           int a[3][3]={0};
           for(int i=0;i<3;i++)
                for(int j=0;j<3;j++)
                 a[i][j]= m_a[i][j] + m.m_a[i][j];
           M33 res(a);
           return res;
   }
   
private:
   int m_a[3][3];
};
int main(void)
{
    int a1[3][3] = {1,2,3,4,5,6,7,8,9};
    int a2[3][3] = {9,8,7,6,5,4,3,2,1};
    M33 m1(a1);
    M33 m2(a2);    
}
  m1    +    m2
1 2 3      9 8 7    10 10 10
4 5 6   +  6 5 4 =  10 10 10
7 8 9      3 2 1    10 10 10
-------
  m1    -    m2
1 2 3      9 8 7    -8 -6 -4
4 5 6   -  6 5 4 =   2  0  2
7 8 9      3 2 1     4  6  8

4 new/delete 操作符 
static void* operator new(size_t size){...}
static void operator delete(void* p){...}

5 函数操作符"()"
 
6 下标操作符"[]"
原文地址:https://www.cnblogs.com/Kernel001/p/7729775.html