例題:定義一個複數類Complex,過載運算子“+”、“=”,“*”,“、”,使之能進行復數的加、減、乘、除。...【面向物件設計】
阿新 • • 發佈:2019-02-04
題目:
定義一個複數類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; }