运算符重载
/*
定义复数类complex,包括私有数据成员实部real和虚部image。定义该类的构造,拷贝构造,析构函数。为该类重载运算符+,-(友元函数),前置和后置++,--(成员函数),插入符和提取符<<,>>(友元函数)。在main函数里定义复数对象,测试重载的这些运算符。
*/
#include<iostream>
#include<string>
using namespace std;
class Complex
{
public:
Complex(int real1=0,int image1=0) :real(real1),image(image1)
{
}
// Complex(Complex & con_recomplex)
// {
// real=con_recomplex.real;
// image=con_recomplex.image;
// cout<<"complex constructor one!"<<endl;
// }
~Complex()
{
};
friend Complex operator+(const Complex &a1, const Complex &a2);
friend Complex operator-(const Complex &a1, const Complex &a2);
Complex operator++();
Complex operator++(int);
Complex operator--();
Complex operator--(int);
friend ostream& operator<<(ostream& os, const Complex&a3);
friend istream& operator>>(istream& is, Complex&a3);
private:
int real;
int image;
};
Complex operator+(const Complex &a1, const Complex &a2)
{
return Complex(a1.real + a2.real, a1.image + a2.image);
}
Complex operator-(const Complex &a1, const Complex &a2)
{
return Complex(a1.real - a2.real, a1.image - a2.image);
}
Complex Complex::operator++()
{
++real;
++image;
return *this;
}
Complex Complex::operator++(int)
{
Complex a = *this;
++(*this);
return a;
}
Complex Complex::operator--()
{
--real;
--image;
return *this;
}
Complex Complex::operator--(int)
{
Complex a = *this;
--(*this);
return *this;
}
ostream& operator<<(ostream& os, const Complex& a3)
{
os<< a3.real << "+" << a3.image << "i";
return os;
}
istream& operator>>(istream& is, Complex&a3)
{
is >> a3.real >> a3.image;
return is;
}
int main()
{
Complex a4(4,5), a5(6,7),a6;
cout << "a4:" << a4 << endl;
cout << "a5:" << a5 << endl;
cin >> a4;cin >> a5;
cout << "重新输入后 a4:" << a4 << endl;
cout << "重新输入后 a5:" << a5 << endl;
a6 = a4 + a5;
cout << a6 << endl;
a6 = a4 - a5;
cout << a6 << endl;
cout <<"++a4:"<<++a4 << endl;
cout <<"a5++:" <<a5++ << endl;
cout << "--a4:" << --a4 << endl;
cout <<"a5-:" << a5-- << endl;
return 0;
}