操作符重载

加号“+”可以用在特定类型间,如int、double等。如果想用在自定义类型间,那么需要重载操作符“+”。

以虚数加法为例,为了方便理解,先用老办法(函数方式myAdd),之后再转换成操作符

#include <iostream>
using namespace std;

class Complex //自定义类,虚数
{
public:
    int m_a; //实部
    int m_b; //虚部
public:
    Complex(int a,int b) //构造函数,带参。Complex类想象成“a+bi”样式
    {
        this->m_a=a;
        this->m_b=b;
    }
};
//全局函数myAdd
Complex myAdd(Complex &c1,Complex &c2) //虚数间相加,返回虚数
{
    Complex tmp(c1.m_a+c2.m_a,c1.m_b+c2.m_b);
    return tmp;
}
int main()
{
    Complex c1(1,2),c2(3,4); //1+2i,3+4i
    Complex c3=myAdd(c1,c2); //4+6i
    cout << c3.m_a<<"+"<<c3.m_b<<"i"<< endl;
    return 0;
}

把myAdd替换成opetator +

#include <iostream>
using namespace std;

class Complex //自定义类,虚数
{
public:
    int m_a; //实部
    int m_b; //虚部
public:
    Complex(int a,int b) //构造函数,带参。Complex类想象成“a+bi”样式
    {
        this->m_a=a;
        this->m_b=b;
    }
};
//operator+等效为全局函数名myAdd
Complex operator+(Complex &c1,Complex &c2) //虚数间相加,返回虚数
{
    Complex tmp(c1.m_a+c2.m_a,c1.m_b+c2.m_b);
    return tmp;
}
int main()
{
    Complex c1(1,2),c2(3,4); //1+2i,3+4i
    //Complex c3=operator+(c1,c2);
    Complex c3=c1+c2; //4+6i
    cout << c3.m_a<<"+"<<c3.m_b<<"i"<< endl;
    return 0;
}

 

结论:operator+就是函数名

posted @ 2020-02-08 17:30  夕西行  阅读(140)  评论(0编辑  收藏  举报