c++复数类

来源:互联网 发布:cf显示客户端数据异常 编辑:程序博客网 时间:2024/06/06 13:00

写一个简单的类完成默认函数和简单的运算符重载

1.完成四个默认成员函数 

2.比较运算符 

3.前置后置++和+/+=的实现 


#ifndef __COMPLEX_H__#define __COMPLEX_H__#define _CRT_SECURE_NO_DEPRECATE 1#include<iostream>#include<stdlib.h>using namespace std;class Complex{public:    Complex (int x,int y)//列表初始化:_real(x),_img(y){}Complex(const Complex& d)//拷贝构造{this->_real = d._real;this->_img = d._img;}~Complex()//析构函数{cout<<"~Complex()"<<endl;}Complex& operator=(const Complex& d)  //赋值运算符的重载{if(&d != this){this->_real = d._real;this->_img = d._img;}return *this;}bool operator>(const Complex & d);Complex& operator+=(const Complex& d);Complex& operator++();Complex operator++(int);void Print_Complex();private:int _real;int _img;};#endif // !__COMPLEX__H_

#include"Complex.h"void Complex::Print_Complex(){if(_img<0)cout<<_real<<_img<<"i"<<endl;elsecout<<_real<<"+"<<_img<<"i"<<endl;}bool Complex::operator>(const Complex& d)                  //比较运算符(复数实不能这样比较大小的,这只是为实现>符号的重载才这样做){return (this->_real)>d._real && ((this->_img) >d._img || (this->_img) == d._img);}Complex& Complex::operator++()        //前置++,默认给实部加1;{this->_real+=1;return *this;}Complex Complex::operator++(int)  //后置++,默认给实部加1;{Complex tmp = *this;this->_real += 1;return tmp;}Complex& Complex::operator+=(const Complex& d)            //预算符+=重载;{this->_real += d._real;this->_img += d._img;return *this;}


原创粉丝点击