題目:
定義一個複數類Complex,重載運算符“+”、“=”,“*”,“、”,使之能進行復數的加、減、乘、除。運算符重載函數作爲Complex類得成員函數。編程序,分別求兩個複數之和、差、積和商。
解答:
#include <iostream>
#include <cmath>
using namespace std;
class Complex{
public:
Complex(double r=0,double i=0);
Complex operator +(const Complex& c);
Complex operator -(const Complex& c);
Complex operator *(const Complex& c);
Complex operator /(const Complex& c);
void print() const;
private:
double real, imag;
};
Complex::Complex(double r,double i){
real=r;
imag=i;
}
Complex Complex::operator +(const Complex& c){
double r=real+c.real;
double i=imag+c.imag;
return Complex(r,i);
}
Complex Complex::operator -(const Complex& c){
double r=real-c.real;
double i=imag-c.imag;
return Complex(r,i);
}
Complex Complex::operator *(const Complex& c){
double r=real * c.real - imag * c.imag;
double i=real * c.imag + imag * c.real;
return Complex(r,i);
}
Complex Complex::operator /(const Complex& c){
double t = pow(c.imag,2) + pow(c.real,2);
double r=real * c.real + imag * c.imag;
double i=imag * c.real -real * c.imag;
return Complex(r/t,i/t);
}
void Complex::print() const{
cout<<'('<<real<<','<<imag<<')'<<endl;
}
int main()
{
Complex a(3,2),b(0,3),c;
c = a + b;
c.print();
c = a - b;
c.print();
c = a * b;
c.print();
c = a / b;
c.print();
return 0;
}