复数类应该具有的操作
运算:+ - * /
比较:==,!=
赋值:=
求模:modulus
技术:操作符重载,使用重载技术对已经存在的操作符进行重载操作
1.利用操作符重载
—-统一复数与实数的运算方式
—-统一复数与实数的比较方式
Complex operator +(const Complex& c);
Complex operator -(const Complex& c);
Complex operator *(const Complex& c);
Complex operator /(const Complex& c);
…….
#ifndef _COMPLEX_H_#define _COMPLEX_H_class Complex{double a;double b;public:Complex(double a = 0,double b = 0);double getA();double getB();double getModulus();Complex operator +(const Complex& c);Complex operator -(const Complex& c);Complex operator *(const Complex& c);Complex operator /(const Complex& c);bool operator ==(const Complex& c);bool operator !=(const Complex& c);Complex operator =(const Complex& c);};#endif#include"complex.h"#include"math.h"Complex::Complex(double a,double b)//default only exist at deleration{this->a = a;this->b = b;}double Complex::getA(){return a;}double Complex::getB(){return b;}double Complex::getModulus(){return sqrt(a*a + b*b);}Complex Complex::operator +(const Complex& c){double na = this->a + c.a;double nb = this->b + c.b;Complex ret(na,nb);return ret;}Complex Complex::operator -(const Complex& c){double na = this->a - c.a;double nb = this->b - c.b;Complex ret(na,nb);return ret;}Complex Complex::operator *(const Complex& c){double na = (this->a * c.a) - (this->b * c.b);double nb = (this->a * c.b) + (this->b * c.a);Complex ret(na,nb);return ret;}Complex Complex::operator /(const Complex& c){double cm = c.a * c.a + c.b* c.b;double na = (this->a * c.a) + (this->b * c.b) / cm;double nb = (this->b * c.a) - (this->a * c.b) / cm;Complex ret(na,nb);return ret;}bool Complex::operator ==(const Complex& c){return (this->a == c.a)&& (this->b == c.b);}bool Complex::operator !=(const Complex& c){return !(*this == c); //巧妙的利用了“==”}Complex& Complex::operator =(const Complex& c){if(this !=&c){this->a = c.a;this->b = c.b;}return *this; //return current}#include<stdio.h>#include"complex.h"int main(){Complex c1(1,2);Complex c2(3,6);Complex c3 = c2 - c1;Complex c4 = c1 * c3;Complex c5 = c2 / c1;printf("c3.a = %f,c3.b = %f\n",c3.getA(),c3.getB());printf("c4.a = %f,c4.b = %f\n",c4.getA(),c4.getB());printf("c5.a = %f,c5.b = %f\n",c5.getA(),c5.getB());Complex c6(2,4);printf("c6 == c3: %d\n",(c6 == c3));printf("c6 != c3: %d\n",(c6 != c3));Complex c7 = c6;printf("c7.a = %f,c7.b = %f\n",c7.getA(),c7.getB());(c3 = c2)= c1; //c3 = c1;printf("c1.a = %f,c1.b = %f\n",c1.getA(),c1.getB());printf("c2.a = %f,c2.b = %f\n",c2.getA(),c2.getB());printf("c3.a = %f,c3.b = %f\n",c3.getA(),c3.getB());return 0;}
注意事项:
1.c++规定赋值操作符(=)只能重载为成员函数
2.操作符重载不能改变原操作符的优先级
3.操作符重载不能改变操作数的个数
4.操作符重载不应该改变操作符的原有语义
小结:
1.复数的概念可以通过自定义类实现
2.复数中的运算操作可以通过操作符重载实现
3.赋值操作符只能通过成员函数实现
4.操作符重载的本质为函数定义
