首页 > 其他 > 详细

关于运算符重载理解

时间:2020-05-24 11:16:50      阅读:62      评论:0      收藏:0      [点我收藏+]

1. 基本概念

   所谓重载,就是重新赋予新的含义。不仅函数可以重载,运算符也可以重载。

   运算符重载的本质是一个函数。

   接下来我们来推演一下运算符重载函数进化为成员函数的过程:

   1)相加函数作为普通函数

class Complex
{
public:
    int a, b;

public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
};

Complex Add(Complex &c1, Complex &c2)
{
    Complex tmp(c1.a + c2.a, c1.b + c2.b);
    return tmp;
}

int main()
{
    Complex c1(1, 2), c2(3, 4);
    // 1 普通函数
    Complex c3 = Add(c1, c2);
    return 0;
}

   2)相加函数作为友元函数

class Complex
{
public:
    int a, b;
    friend Complex operator+(Complex &c1, Complex &c2);

public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
};

Complex operator+(Complex &c1, Complex &c2)
{
    Complex tmp(c1.a + c2.a, c1.b + c2.b);
    return tmp;
}

int main()
{
    Complex c1(1, 2), c2(3, 4);
    // 2 友元函数
    Complex c3 = operator+(c1, c2);
    return 0;
}

   3)相加函数作为类成员函数

class Complex
{
public:
    int a, b;
    Complex operator+(Complex &c2)
    {
        Complex tmp;
        tmp.a = this->a + c2.a ;
        tmp.b = this->b + c2.b ;
        return tmp;
    }

public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
};

int main()
{
    Complex c1(1, 2), c2(3, 4);
    // 3 成员函数
    Complex c3 = c1 + c2;
    return 0;
}

 

  

 

 

 

 

未完待续。。。。。。

关于运算符重载理解

原文:https://www.cnblogs.com/yanghh/p/12945941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!