两个反思点:
在使用流运算符时需要使用友元函数。
在实战中,运算符的重载若为成员函数其参数必须少于2两个,即最多一个参数。所以流运算符需要有两个参数,但是它又必须调用类里的私有成员,所以就使用了友元函数的方法。
其余都是比较easy的。
#include <iostream>
using namespace std;
class Complex
{
private:
double real;
double image;
public:
Complex(const Complex& complex) :real{ complex.real }, image{ complex.image } {
}
Complex(double Real=0, double Image=0) :real{ Real }, image{ Image } {
}
Complex operator=(const Complex& a);
Complex operator+(const Complex& a);
Complex operator-(const Complex& a);
Complex operator*(const Complex& a);
Complex operator/(const Complex& a);
friend ostream& operator<<(ostream &out, const Complex &a);
friend istream& operator>>(istream &in, Complex &a);
};
Complex Complex::operator+(const Complex &b)
{
return Complex(real + b.real, image + b.image);
}
Complex Complex::operator-(const Complex& b){
return Complex(real-b.real, image-b.image);
}
Complex Complex::operator*(const Complex& b){
return Complex(real*b.real-image*b.image, real*b.image+image*b.real);
}
Complex Complex::operator/(const Complex& b){
Complex temp(real, image);
int dom = b.real * b.real + b.image * b.image;
Complex son = Complex(b.real/dom, -b.image/dom);
return Complex(temp*son);
}
ostream& operator<<(ostream &out, const Complex &a){
if(a.image>=0){
return out << "(" << a.real << "+" << a.image << "i)" ;
}else{
return out << "(" << a.real << a.image << "i)" ;
}
}
istream& operator>>(istream &in, Complex &a){
return in >> a.real >> a.image;
}
int main()
{
Complex z1, z2;
cin >> z1;
cin >> z2;
cout << z1 << " " << z2 << endl;
cout << z1 + z2 << endl;
cout << z1 - z2 << endl;
cout << z1 * z2 << endl;
cout << z1 / z2 << endl;
return 0;
}