C++ Complex复数类

来源:互联网 发布:云上贵州大数据比赛 编辑:程序博客网 时间:2024/05/17 08:43

#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>using namespace std;class Complex{public:Complex(double real = 0, double image = 0):_real(real),_image(image){}Complex(const Complex& d):_real(d._real),_image(d._image){}void Display(){cout<<"real:"<<_real<<"image:"<<_image<<endl;}Complex operator +(const Complex& d)//复数相加{Complex tmp = *this;tmp._real += d._real;tmp._image += d._image;return tmp;}Complex& operator +=(const Complex& d)//复数的加等,返回值用引用{_real += d._real;_image += d._image;return *this;}Complex& operator ++()//复数的前置++,返回值用引用{_real++;return *this;}Complex operator ++(int)//复数的后置++{Complex tmp = *this;_real++;return tmp;}//减法与加法相似//Complex operator -(const Complex& d)//Complex& operator -=(const Complex& d)//Complex& operator --()//Complex operator --(int)//复数不能比较大小(复数有方向)所以这里就不实现了^-^//operator >//operator >=//operator <//operator <=bool operator ==(const Complex& d)//复数的=={return (_real == d._real)&& (_image == d._image);}bool operator !=(const Complex& d)//复数的!={return (_real != d._real)|| (_image != d._image);}Complex operator *(const Complex& d)//复数相乘{Complex tmp;tmp._real = (_real*d._real) - (_image*d._image);tmp._image = (_real*d._image) + (_image*d._real);return tmp;}Complex operator /(const Complex& d)//复数相除{Complex tmp;tmp._real= ((_real*d._real) - (_image*d._image))      /((d._real)*(d._real) + (d._image)*(d._image));tmp._image = (_real*d._image) + (_image*d._real)  /((d._real)*(d._real) + (d._image)*(d._image));return tmp;}private:double _real;double _image;};void test1()//测试加减相关函数{Complex d1(1, 1);Complex d2(2, 2);Complex d3;d3 = d1 + d2;d3.Display();d3 = d1++;d3.Display();d3 = d1+=(d2);d3.Display();d3 = ++d1;d3.Display();}void test2()//测试乘除/==/!={int a = -1;Complex d1(1, 1);Complex d2(2, 2);Complex d3;d3 = d1*(d2);d3.Display();d3 = d1/(d2);d3.Display();a = d1==(d2);cout<<"operator ==():"<<a<<endl;a = d1!=(d2);cout<<"operator !=():"<<a<<endl;}int main(){test1();test2();return 0;}


原创粉丝点击