操作符重载_复数运算

来源:互联网 发布:java jface 编辑:程序博客网 时间:2024/06/16 19:38

题目:
要求实现复数的显示,两个复数的加减,比较:

#include<iostream>using namespace std;class Ccomplex{    double real,imag;public:    Ccomplex(){real=0;imag=0;}  //定义构造函数    Ccomplex(double r,double i){real=r;imag=i;} //重载构造函数    Ccomplex(const Ccomplex &c){real=c.real;imag=c.imag;}   //拷贝构造函数    ~Ccomplex(){}   //析构函数    void ShowComplex(); //显示复数    Ccomplex operator+=(const Ccomplex& c); //+=操作符重载    Ccomplex operator-=(const Ccomplex& c); //-=操作符重载    bool operator<(const Ccomplex& c);  //< 操作符重载    bool operator>(const Ccomplex& c);  //< 操作符重载    bool operator==(const Ccomplex& c); //==操作符重载};void Ccomplex::ShowComplex(){    (imag<0)?(cout<<real<<imag<<"i"<<endl):(cout<<real<<"+"<<imag<<"i"<<endl);}Ccomplex Ccomplex::operator+=(const Ccomplex& c){    Ccomplex c1;    c1.real=real+c.real;    c1.imag=imag+c.imag;    return c1;}Ccomplex Ccomplex::operator-=(const Ccomplex& c){    Ccomplex c1;    c1.real=real-c.real;    c1.imag=imag-c.imag;    return c1;}bool Ccomplex::operator<(const Ccomplex& c){    return (real<c.real)?true:false;}bool Ccomplex::operator>(const Ccomplex& c){    return (real>c.real)?true:false;}bool Ccomplex::operator==(const Ccomplex& c){    return (real==c.real&&imag==c.imag)?true:false;}int main(){    Ccomplex test1(11,22);    cout<<"复数test1:";    test1.ShowComplex();    Ccomplex test2(33,44);    cout<<"复数test2:";    test2.ShowComplex();    cout<<"----调用+=运算符-----"<<endl;    Ccomplex test3=test1 += test2;    cout<<"复数test3:";    test3.ShowComplex();    cout<<"----调用-=运算符-----"<<endl;    Ccomplex test4=test1-=test2;    cout<<"复数test4:";    test4.ShowComplex();    cout<<"----调用< 和 > 操作符-----"<<endl;    (test1>test2)?(cout<<"test1>test2"<<endl):(cout<<"test2>test1"<<endl);    cout<<"----调用==操作符----------"<<endl;    Ccomplex test5=test1;    cout<<"test5:";    test5.ShowComplex();    (test1==test5)?(cout<<"test1==test5"<<endl):(cout<<"test1!=test5"<<endl);    (test1==test2)?(cout<<"test1==test2"<<endl):(cout<<"test1!=test2"<<endl);    return 0;}
0 0
原创粉丝点击