• C++语法小记---运算符重载


    运算符重载
    • 运算符重载的本质也是对已有功能的扩展

    • 运算符重载的本质就是函数重载,只是函数变成了 operator + 运算符

    • 当成员函数和全局函数对运算符进行重载时,优先调用成员函数

    • 运算符重载为成员函数时,可以少一个参数,调用时,以右参数为参数进行函数调用

    • 不可以重载的运算符: . :: sizeof ?:

    • 运算符重载不改变参数个数,优先级,结合性

    例子

    • 成员函数重载
     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class Test
     6 {
     7 private:
     8     int a;
     9     
    10 public:
    11     Test() {a = 0;}
    12     
    13     Test(int a) {this->a = a;}
    14     
    15     void show()
    16     {
    17         cout << "a = " << a << endl;
    18     }
    19 
    20     Test operator + (Test& t)
    21     {
    22         Test rtn(0);
    23         rtn.a = this->a + t.a;
    24         return rtn;
    25     }    
    26 };
    27 
    28 int main()
    29 {
    30     Test t, t1(1), t2(2);
    31     t = t1.operator + (t2);  //等同于 t = t1 + t2;
    32     t.show();
    33     return 0;
    34 }
    • 全局函数重载
     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class Test
     6 {
     7 private:
     8     int a;
     9     
    10 public:
    11     Test() {a = 0;}
    12     
    13     Test(int a) {this->a = a;}
    14     
    15     int getA() {return a;}
    16     
    17     void setA(int a) {this->a = a;}
    18     
    19     void show()
    20     {
    21         cout << "a = " << a << endl;
    22     }    
    23 };
    24 
    25 Test operator + (Test& t1, Test& t2)
    26 {
    27     Test rtn(0);
    28     rtn.setA(t1.getA() + t2.getA());
    29     return rtn;
    30 }    
    31 
    32 int main()
    33 {
    34     Test t, t1(1), t2(2);
    35     t = t1 + t2;
    36     t.show();
    37     return 0;
    38 }
    重载数组操作符
    • 重载数组操作符只能是成员函数

    • 重载数组操作符的参数只能是一个,但是类型可以改变

    • 标准库中的string类,可以按照数组的方式访问

    1 class Test
    2 {
    3     int data[10];
    4 public:
    5     int& operator [] (int i)
    6     {
    7         return data[i];
    8     }
    9 }
  • 相关阅读:
    ffmpeg 合并文件
    win10 设备摄像头,麦克风,【隐私】权限
    负载均衡,过载保护 简介
    《用Python做科学计算》 书籍在线观看
    Getting Started with OpenMP
    Algorithms & Data structures in C++& GO ( Lock Free Queue)
    PostgreSQL新手入门
    Ubuntu 网络配置
    QT 4.7.6 驱动 罗技C720摄像头
    使用vbs脚本添加域网络共享驱动器
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11294634.html
Copyright © 2020-2023  润新知