首页 > 其他分享 >Class 复数类运算符重载

Class 复数类运算符重载

时间:2023-01-18 00:12:18浏览次数:57  
标签:real return ++ 运算符 operator Complex 重载 -- Class

(1条消息) 运算符重载 前缀++ 后缀++_peng864534630的博客-CSDN博客_运算符重载前缀和后缀

#include <iostream>
using namespace std;
class Complex
{
    public:
    Complex(){real=0;imag=0;}
    Complex(double r,double i)
    {
        real=r;
        imag=i;
    }
    Complex operator +(Complex &c2);
    Complex operator -(Complex &c2);
    Complex operator *(Complex &c2);
    Complex operator /(Complex &c2);
    const Complex operator ++(int);//对后缀自增自减的处理 
    const Complex operator --(int);
    friend ostream & operator <<(ostream &os,const Complex &c);
    friend istream & operator <<(istream &is,Complex &c);
    Complex operator ++();
    Complex operator --();
    void display();
    double real;
    double imag;
};
Complex Complex::operator +(Complex &c2)
{
    Complex c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}
Complex Complex::operator -(Complex &c2)
{
    Complex c;
    c.real=real-c2.real;
    c.imag=imag-c2.imag;
    return c;
}
Complex Complex::operator *(Complex &c2)
{
    Complex c;
    c.real=real*c2.real-imag*c2.imag;
    c.imag=real*c2.imag+imag*c2.real;
    return c;
}
Complex Complex::operator /(Complex &c2)
{
    Complex c;
    c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
    c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
    return c;
}
ostream & operator <<(ostream & os,const Complex & c )
{
    os<<c.real<<"+"<<c.imag<<"i";
    return os;
}
istream & operator >>(istream & is,Complex &c)
{
    cout<<"input real part and imaginary part of complex number:";
    is>>c.real>>c.imag;
    return is;
}
Complex Complex::operator ++()
{
    real++;
    return *this;
}
Complex Complex::operator --()
{
    real--;
    return *this;
}
const Complex Complex::operator ++(int)
{
    Complex T;
    T=*this;
    real++;
    return T;
} 
const Complex Complex::operator --(int)
{
    Complex T;
    T=*this;
    real--;
    return T;
} 
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
 int main(){
    Complex c1(1,2),c2(3,-4);
    cout << (c1+c2) << endl;
    cout << c1-c2 << endl;
    cout << c1*c2 << endl;
    cout << c1/c2 << endl;
    cout << ++c1 << endl;
    cout<<c1++<<endl;
    cout << c1 << endl;
    cout << --c2 << endl;
    cout<<c2--<<endl; 
    return 0;
}

 

标签:real,return,++,运算符,operator,Complex,重载,--,Class
From: https://www.cnblogs.com/XLINYIN/p/17058976.html

相关文章