复数类
复数包含实部和虚部,表示为:a+bi 的形式
复数可以比较两个复数的大小;
两个复数是否相等;
复数前置后置自增自减等操作。
#include <iostream> using namespace std; class Complex { public: //四个默认成员函数 //构造函数 Complex(double real=0.0, double image=0.0) { _real = real; _image = image; } //拷贝构造函数 Complex(const Complex& c) { _real = c._real; _image = c._image; } //析构函数 ~Complex() { cout<<"析构函数"<<endl; } //赋值操作符的重载 Complex& operator=(const Complex& c) { _real = c._real; _image = c._image; return *this; } public: Complex operator+(const Complex& c) { Complex tmp = 0; tmp._real = _real + c._real; tmp._image = _image + c._image; return tmp; } Complex& operator+=(const Complex& c) { _real = _real + c._real; _image = _image + c._image; return *this; } Complex operator-(const Complex& c) { Complex tmp = 0; tmp._real = _real - c._real; tmp._image = _image - c._image; return tmp; } Complex& operator-=(const Complex& c) { _real = _real - c._real; _image = _image - c._image; return *this; } bool operator==(const Complex& c) { if((_real == c._real)&&(_image == c._image)) { return true; } else { return false; } } bool operator!=(const Complex& c) { if((_real == c._real)&&(_image == c._image)) { return false; } else { return true; } } //前置++ Complex& operator++() { this->_real++; this->_image++; return *this; } //后置++ Complex operator++(int) { Complex tmp(*this); this->_real++; this->_image++; return tmp; } //前置-- Complex& operator--() { this->_real--; this->_image--; return *this; } //后置-- Complex operator--(int) { Complex tmp(*this); this->_real--; this->_image--;
测试代码如下:
int main() { Complex c1(3.0,5.0); Complex c2(3.0,5.0); Complex tmp(0.0,0.0); //tmp = c1+c2; //tmp = c1.operator+(c2) +运算符重载 //c1+=c2; //c1 = c1.operator+=(c2) +=运算符重载 //tmp = c1-c2 //tmp = c1.operator-(c2) -运算符重载 //c1-=c2; //c1 = c1.ioerator-=(c2) -=运算符重载 /*if(c1==c2) // ==判断两个复数类对象是否相等 { cout<<"相等"<<endl; } else { cout<<"不等"<<endl; }*/ tmp = c1++; //后置++ tmp = ++c1; //前置++ tmp = c1--; //后置-- tmp = --c1; //前置-- c1.Display(); c2.Display(); tmp.Display(); return 0; } return tmp; } void Display() { cout<<_real<<"+"<<_image<<"i"<<endl; } private: double _real; double _image; };