# pragma once//头文件 class Complex { public: Complex(double Real = 0, double Imag = 0);//构造函数 ~Complex(); Complex& operator =(Complex& Num);//拷贝 Complex operator +(const Complex& Num);//复数加法 Complex operator -(const Complex& Num);//复数减法 Complex operator *(const Complex& Num);//复数乘法 Complex operator /(const Complex& Num);//复数除法 Complex& operator +=(const Complex& Num); bool operator > (const Complex& Num);//大于 bool operator <=(const Complex& Num);//小 等 void Print_Complex();//打印复数 private: double _real;//实部 double _imag;//虚部 }; #include<iostream>//函数文件 #include"complex.h" using namespace std; Complex::Complex(double Real , double Imag )//构造函数 { _real = Real; _imag = Imag; } Complex::~Complex() { } Complex& Complex:: operator=(Complex& Num)//拷贝构造 { _real = Num._real; _imag = Num._imag; return *this; } Complex Complex:: operator +(const Complex& Num)//复数加法 { Complex tmp; tmp._real = _real + Num._real; tmp._imag = _imag + Num._imag; return tmp; } Complex Complex:: operator -(const Complex& Num)//复数减法 { Complex tmp; tmp._real = _real - Num._real; tmp._imag = _imag - Num._imag; return tmp; } Complex Complex::operator *(const Complex& Num)//复数乘法 { double tmpReal = this->_real; double tmpImag = this->_imag; Complex tmp; tmp._real = _real *Num._real - _imag *Num._imag ; tmp._imag = tmpImag* Num._real + tmpReal* Num._imag; return tmp; } Complex Complex:: operator /(const Complex& Num)//复数除法 { if (Num._imag == 0 && Num._real == 0) exit(-1); double tmpReal = this->_real; double tmpImag = this->_imag; Complex tmp; tmp._real = (_real *Num._real + _imag *Num._imag) / (Num._imag*Num._imag + Num._real*Num._real); tmp._imag = (tmpImag* Num._real - tmpReal* Num._imag) / (Num._imag*Num._imag + Num._real*Num._real); return tmp; } Complex& Complex::operator +=(const Complex& Num) { _real = _real + Num._real; _imag = _imag + Num._imag; return *this; } void Complex::Print_Complex()//打印复数 { if (this->_imag) cout <<this->_real << "+" << this->_imag << "i" << endl; else cout << this->_real << endl; } bool Complex::operator > (const Complex& num) { return (_real*_real + _imag*_imag )>( num._real*num._real + num._imag*num._imag); } bool Complex::operator <=(const Complex& num) { return !(*this > num); } #include<iostream>//主函数测试函数 #include"complex.h" using namespace std; void test1() { Complex com1(1, 2); Complex com2(3, 4); Complex com3(1, 1); com3 = com1 - com2; com3.Print_Complex(); com3 = com1 + com2; com3.Print_Complex(); com3 = com1*com2; com3.Print_Complex(); com3 = com1 / com2;//(ac+bd)/(c^2+d^2) +(bc-ad)/(c^2+d^2)i com3.Print_Complex(); } int main() { test1(); return 0; }
原文:http://shaungqiran.blog.51cto.com/10532904/1713434