运算符重载函数

#if 1
#include <iostream>

using namespace std;

class complex
{
public:
    complex():real(0),imag(0){}//无参/缺省构造函数
    complex(double real, double imag);//带参构造函数
    complex(const complex &c);//拷贝函数
    complex &operator=(const complex &right);//赋值运算符函数,重载在成员函数上
    ~complex(){}//析构函数,自动调用,只有在释放内存的时候会在delete后面先析构,其余的在return之前一步析构
    complex & operator++();//所有一元符号都重载在成员函数上(前置)先加后用
    complex  operator++(int);//(后置)
    complex &operator+=(const complex &righr);//具有自赋值性质的二元运算符重载在重载在成员函数上
    friend complex operator+(const complex &right,const complex &right1);//没有自赋值的二元运算符重载在友元函数上,友元函数只是比成员函数多了一个fried和一个参数
    void display();
private:
    int real;
    int imag;

};
complex operator+(const complex &right,const complex &right1)
{
    complex temp;
    temp.real = right.real + right1.real;
    temp.imag = right.imag + right1.imag;
    return temp;
}
complex & complex::operator +=(const complex &right)
{
    real += right.real;
    imag += right.imag;
    return *this;
}
complex complex::operator++(int)
{
    complex temp = *this;//调用拷贝函数,使得temp拥有了返回对象本身的意义,最后返回了temp,一来一去等于没变,就实现了先用后加
    ++real;
    ++imag;
    return temp;//局部变量用完会消失,因此不用引用符号(但是会返回出去,并不冲突)
}
complex & complex::operator++()
{
    ++real;
    ++imag;
    return *this;//this指向调用它的函数
}

complex::complex(double real, double imag):real(real),imag(imag){}

complex::complex(const complex &right)
{
    real=right.real;
    imag=right.imag;
}

complex& complex::operator=(const complex &right)
{
    if(this==&right)
    {
        return *this;
    }
    real=right.real;
    imag=right.imag;

    return *this;
}

void complex::display()
{
    if((real!=0)||(real==0&&imag==0))
    {
        cout << real;
    }

    if (imag ==1)
        cout << "+" <<"i";
    else if(imag >0)
    {
        cout <<"+" << imag << "i" <<endl;
    }
    else if (imag < 0)
    {
        cout << imag <<"+" <<"i" <<endl;
    }
    else if (imag == -1)
    {
        cout << "-" << imag << "i" <<endl;
    }
    else
        ;
    cout <<endl;
    return ;
}

int main()
{
    complex complex1(2,3),complex3,complex4,complex5,complex7;
    complex complex6(2,3);
    complex1.display();//2+3i
    complex complex2 = complex1;//拷贝运算符
    complex2.display();//2+3i
    complex3 = complex1;//赋值运算符
    complex3.display();//2+3i
    complex4 = ++complex1;//前置自加
    complex4.display();//3+4i
    complex1.display();//3+4i
    complex5 = complex1++;//后置自加
    complex5.display();//3+4i
    complex1.display();//4+5i
    complex6 +=complex1;//自赋值运算符
    complex6.display();//6+8i
    complex1.display();//4+5i
    complex7 = complex2 + complex3;//加号运算符,没有自赋值性质的要重载在友元函数上
    complex7.display();//4+6i

    return 0;
}
#endif
  

 

posted @ 2021-03-15 20:28  z79  阅读(132)  评论(0)    收藏  举报