最近学习C++时,为了充分认识运算符重载自己在闲暇时间谢了一个complex类,现在放上来和大家共享共享:
首先看到的是头文件
#ifndef COMPLEX_H
#define COMPLEX_H
#include<iostream>
using namespace std;
class Complex
{
friend Complex operator+(const Complex&,const Complex&);
friend Complex operator-(const Complex&,const Complex&);
friend Complex operator*(const Complex&,const Complex&);
friend Complex operator/(const Complex&,const Complex&);
friend istream& operator>>(istream&,Complex&);
friend ostream& operator<<(ostream&,const Complex&);
public:
Complex(const Complex&);
Complex(int real = 0,int imag = 0);
virtual ~Complex();
Complex& operator++();
Complex operator++(int index);
Complex& operator--();
Complex operator--(int index);
operator bool();
operator string();
private:
int real;
int imag;
};
#endif // COMPLEX_H
代码文件中定义了Complex的简单的一些使用操作。
下面是对这些操作的主要实现:
#include "Complex.h" #include<iostream> #include<cstdlib> using namespace std; Complex::Complex(const Complex& souceComplex) { real = souceComplex.real; imag = souceComplex.imag; } Complex::Complex(int real,int imag):real(real),imag(imag){} Complex::~Complex(){} Complex& Complex::operator++() { ++real; ++imag; return *this; } Complex Complex::operator++(int index) { Complex temp; ++real; ++imag; return temp; } Complex& Complex::operator--() { --real; --imag; return *this; } Complex Complex::operator--(int index) { Complex temp; --real; --imag; return temp; } Complex operator+(const Complex& first,const Complex& second) { Complex temp; temp.real = first.real+second.real; temp.imag = first.imag+second.imag; return temp; } Complex operator-(const Complex& first,const Complex& second) { Complex temp; temp.real = first.real-second.real; temp.imag = first.imag-second.imag; return temp; } Complex operator*(const Complex& first,const Complex& second) { Complex temp; temp.real = first.real*second.real-first.imag*second.imag; temp.imag = first.imag*second.real+second.imag*first.real; return temp; } Complex operator/(const Complex& first,const Complex& second) { Complex temp; return temp; } istream& operator>>(istream& in,Complex& souce) { cout<<"Please input real and image:"<<endl; in>>souce.imag>>souce.real; return in; } ostream& operator<<(ostream& out,const Complex& result) { cout<<"The Comples is:"<<endl; out<<'<'<<result.real<<'+'<<result.imag<<"i>"<<endl; return out; } Complex::operator bool() { bool flag = false; if(real>0) { flag = true; } return flag; } Complex::operator string() { char* str; str = (char*)malloc(sizeof(char)*20); int count = 0; while(real/10!=0) { int temp = real/10; str[count] = temp+'0'; ++count; } str[count] = real%10+'0'; ++count; str[count]='+'; while(imag/10!=0) { int temp = imag/10; str[count] = temp+'0'; ++count; } ++count; str[count] = imag%10+'0'; ++count; str[count]='i'; ++count; str[count]='\0'; return str; }
以上就是个人在学习运算符重载时做的一个简单的Complex,不是很好需要完善。