c++学习笔记之加法运算符重载

目录

运算符重载

加法运算符重载

成员函数重载+号

全局函数重载+号


运算符重载


    运算符重载概念:对已有的运算符重新定义,赋予其另一种功能,以适应不同的数据类型

加法运算符重载


    作用:实现两个自定义数据类型相加的运算
    方法:


成员函数重载+号


            示例:
 

                //成员函数重载
                Preson operator+(Preson &p) 
                {
                    Preson temp;
                    temp.m_A = this->m_A + p.m_A;
                    temp.m_B = this->m_B + p.m_B;
                    return temp;
                }


全局函数重载+号


            示例:

                //全局函数重载
                Preson operator+(Preson& P1, Preson& P2)
                {
                    Preson temp;
                    temp.m_A = P1.m_A + P2.m_A;
                    temp.m_B = P1.m_B + P2.m_B;
                    return temp;
                }

    注:
        Preson P3 = P1 + P2;//经过编译器简化
        Preson P4 = operator+(P1, P2);//运算符重载的本质 

    再注:
        1)对于内置的数据类型的表达式的运算符式不可改变的(就是自带的,已经设定好的,比如1+1 = 2,1-1 = 0;这些不能该,人家本来就有,改它干嘛,没有意义)
        2)不要滥用运算符重载(就是operator后面写了个+号,但是你内部函数实现的确实-号,这样虽然没错,但是别人看你代码容易影响心态)      

 示例:

            #include <iostream>
            using namespace std;

            class Preson {
            public:
                Preson()
                {
                    m_A = 10;
                    m_B = 10;
                }

                //成员函数重载
                /*Preson operator+(Preson &p) 
                {
                    Preson temp;
                    temp.m_A = this->m_A + p.m_A;
                    temp.m_B = this->m_B + p.m_B;
                    return temp;
                }*/

            public:
                int m_A;
                int m_B;
            };

            //全局函数重载
            Preson operator+(Preson& P1, Preson& P2)
            {
                Preson temp;
                temp.m_A = P1.m_A + P2.m_A;
                temp.m_B = P1.m_B + P2.m_B;
                return temp;
            }

            void test01()
            {
                Preson P1;
                Preson P2;
                Preson P3 = P1 + P2;//经过编译器简化
                Preson P4 = operator+(P1, P2);//运算符重载的本质
                cout << "P3中m_A的值 = " << P3.m_A << endl;
                cout << "P3中m_B的值 = " << P3.m_B << endl;
                cout << "P4中m_A的值 = " << P4.m_A << endl;
                cout << "P4中m_B的值 = " << P4.m_B << endl;
            }

            int main()
            {
                test01();
                system("pause");

                return 0;
            }

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值