您的位置:首页 > 编程语言 > C语言/C++

c++运算符重载

2014-10-02 20:09 232 查看
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: