zoukankan      html  css  js  c++  java
  • 运算符重载

    加号运算符重载

    如果想让自定义数据类型 进行+运算,那么就需要重载 + 运算符

    在成员函数 或者 全局函数里 重写一个+运算符的函数

    函数名 operator+ () {}

    运算符重载 也可以提供多个版本

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
        Person() {};
        Person(int a, int b) :m_A(a), m_B(b)
        {
    
        }
    
        //Person operator+(Person& p)        //成员函数重载加法运算符 二元
        //{
        //    Person tmp;                    //需要提供默认的构造函数
        //    tmp.m_A = this->m_A + p.m_A;
        //    tmp.m_B = this->m_B + p.m_B;
        //    return tmp;
        //}
    
        int m_A;
        int m_B;
    };
    
    //全局函数重载+号运算符 二元
    Person operator+(Person& p1, Person& p2)
    {
        Person tmp;
        tmp.m_A = p1.m_A + p2.m_A;
        tmp.m_B = p1.m_B + p2.m_B;
        return tmp;
    }
    //重载+号运算符多版本 即(重载重载+号运算符)
    Person operator+(Person& p1, int a)
    {
        Person tmp;
        tmp.m_A = p1.m_A + a;
        tmp.m_B = p1.m_B + a;
        return tmp;
    }
    void test()
    {
        Person p1(10, 10);
        Person p2(10, 10);
        Person p3 = p1 + p2;    //p1+p2 从什么表达是转变? 成员 p1.operator(p2)  全局 operator(p1,p2)
        cout << "p3.m_A:" << p3.m_A << "p3.m_B:" << p3.m_B << endl;
        Person p4 = p1 + 20;
        cout << "p4.m_A:" << p4.m_A << "p4.m_B:" << p4.m_B << endl;
    
    }
    
    int main()
    {
        test();
        system("Pause");        //阻塞功能
        return EXIT_SUCCESS;    // 返回正常退出
    }

    结果:

  • 相关阅读:
    java读取ANSI编码或者UTF8编码文件乱码问题解决
    java集合框架(Framework)的性能
    堆排序程序
    Python监控Apache,MySQL
    堆排序和快速排序性能比较
    资源管理命令
    Python监控Apache,MySQL
    资源管理命令
    javap反编译
    浏览器的用户代理字符串
  • 原文地址:https://www.cnblogs.com/yifengs/p/15171843.html
Copyright © 2011-2022 走看看