c++运算符重载

<span style="font-size:18px;">#include<iostream>
using namespace std;

class Complex
{
public:
 Complex(){real=0,image=0;};
          Complex(double,double);
 
 Complex operator++(int);
 Complex& operator++();
 Complex& operator--();

 Complex operator+(const Complex &);
 Complex operator-(const Complex &);
 Complex operator*(const Complex &);

 //Complex& operator+=(Complex &);
 //Complex& operator-=(Complex &);
 //iostream & operator<<(iostream &);
 //iostream & operator>>(iostream &);
 double getReal();
 double getimage();
//private:
double real;
double image;
};

Complex::Complex(double r,double i)
{
 real=r;
 image=i;
};


Complex& Complex::operator++()
{
    real++;
image++;
return *this;
}

Complex Complex::operator++(int a)
{
    Complex temp=*this;
real++;
image++;
return temp;
}


Complex& Complex::operator--()
{
        real--;
image--;
return *this;
};

Complex Complex::operator+(const Complex &a)
{
   return Complex(real+a.real,image+a.image);
};


Complex Complex::operator-(const Complex &a)
{
   return Complex(real-a.real,image-a.image);
};

 Complex Complex::operator*(const Complex &a)
{
  return Complex(real*a.real,image*a.image);
};


/*Complex& Complex::operator+=(Complex &a)
{
   real+=a.real;
   image+=a.image;
   return *this;
};*/




/*Complex& Complex::operator-=(Complex &a)
{
  real-=a.real;
  image-=a.image;
  return *this;
};*/


Complex& operator+=(Complex &a,const Complex &b)
{
   a.real+=b.real;
   a.image+=b.image;
   return a;
};


Complex& operator-=(Complex &a,const Complex &b)
{
   a.real-=b.real;
   a.image-=b.image;
   return a;
};


ostream &operator<<( ostream &out,const Complex &a)
{
  //out<<"("<<a.real<","<<a.image<<")"<<endl;
  out<<"("<<a.real<<","<<a.image<<")";
  
  return out;
};


istream &operator>>(istream &in,Complex &a)
{
in>>a.real>>a.image;
    return in;
};



int  main()
{
  Complex a;
  cout<<"请输入一个复数:"<<endl;
  cin>>a;
  cout<<"你输入的数是:"<<a<<endl;
  
  Complex b;
 
  cout<<"a:"<<a<<" b:"<<b<<endl;
  b=a++;
  cout<<"b=a++ :"<<b<<endl;


 
  cout<<"a:"<<a<<" b:"<<b<<endl;
  b=++a;
  cout<<"b=++a :"<<b<<endl;


  b=Complex(10,10);


  Complex c;
  c=a+b;
  cout<<"a:"<<a<<" b:"<<b<<endl;
  cout<<"a+b:"<<c<<endl;
  c=a-b;
  cout<<"a:"<<a<<" b:"<<b<<endl;
  cout<<"a-b: "<<c<<endl;
  c=a*b;
  cout<<"a:"<<a<<" b:"<<b<<endl;
  cout<<"a*b: "<<c<<endl;


  
  cout<<"a:"<<a<<" b:"<<b<<endl;
  a+=b;
  cout<<"a+=b: "<<a<<endl;
 
  cout<<"a:"<<a<<" b:"<<b<<endl;
  a-=b;
  cout<<"a-=b: "<<a<<endl;

//之前我定义了一个条件编译条件没想到  编译器中居然有相同的宏 结果老是编译不过去 坑!!
//#ifndef COMPLEX_H
//cout<<"error!!"<<endl;
//#endif

  return 0; 
}</span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值