习题 10.2 定义一个复数类Complex,重载运算符+,-,*,/,使之能用于复数的加、减、乘、除。运算符重载函数作为Complex类的成员函数。编程序,分别求两个复数之和、差、积和商。
代码:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0.0,double i = 0.0):real(r),imag(i) {}
Complex operator+(Complex );
Complex operator-(Complex );
Complex operator*(Complex );
Complex operator/(Complex );
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(Complex c)
{
return Complex(this->real + c.real, this->imag + c.imag);
}
Complex Complex::operator-(Complex c)
{
return Complex(this->real - c.real, this->imag - c.imag);
}
Complex Complex::operator*(Complex c)
{
return Complex(this->real * c.real, this->imag * c.imag);
}
Complex Complex::operator/(Complex c)
{
return Complex(this->real / c.real, this->imag / c.imag);
}
void Complex::display()
{
cout << "