例题:定义一个复数类Complex,重载运算符“+”、“=”,“*”,“、”,使之能进行复数的加、减、乘、除。...【面向对象设计】

题目:

定义一个复数类Complex,重载运算符“+”、“=”,“*”,“、”,使之能进行复数的加、减、乘、除。运算符重载函数作为Complex类得成员函数。编程序,分别求两个复数之和、差、积和商。

解答: 

#include 
#include 
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<<'('<

 

你可能感兴趣的:(面向对象设计)