测试而已,不完整。
complex.h
#ifndef _COMPLEX_H
#define _COMPLEX_H
class complex{
public://构造函数
complex():_real(0),_imag(0){}
complex(double real):_real(real),_imag(0){}
complex(double real,double imag):_real(real),_imag(imag){}
public://设置和获取实部和虚部的值
double GetReal() const{return _real;}//获取实部的值
double GetImag() const{return _imag;}//获取虚部的值
void SetReal(double real); //更改实部的值
void SetImag(double imag); //更改虚部的值
void SetVal(double real,double imag); //更改整个复数
public:
friend complex operator+(const complex &lhs,const complex &rhs);
// complex& operator+ (const complex &val);
complex& operator* (const complex &val);
complex& operator+=(const complex &val);
complex& operator*=(const complex &val);
friend bool operator==(const complex &lhs,const complex &rhs);
friend bool operator!=(const complex &lhs,const complex &rhs);
private:
double _real;//实部
double _imag;//虚部
};
#endif
complex.cpp
#include <stdafx.h>
#include "complex.h"
void complex::SetReal(double real)
{
_real = real;
}
void complex::SetImag(double imag)
{
_imag = imag;
}
void complex::SetVal(double real,double imag)
{
_real = real;
_imag = imag;
}
///
complex operator+ (const complex &lhs,const complex &rhs)
{
return complex(lhs._real+rhs._real,lhs._imag+rhs._imag);
}
complex& complex::operator* (const complex &val)
{
complex temp(*this);
temp *= val;
return temp;
}
complex& complex::operator+=(const complex &val)
{
_real += val._real;
_imag += val._imag;
return *this;
}
complex& complex::operator*=(const complex &val)
{
double retReal = _real;
double retImag = _imag;
_real = retReal*val._real - retImag*val._imag;
_imag = retReal*val._imag + retImag*val._real;
return *this;
}
bool operator==(const complex &lhs,const complex &rhs)
{
return (lhs._real == rhs._real) && (lhs._imag == rhs._imag);
}
bool operator!=(const complex &lhs,const complex &rhs)
{
return !(lhs==rhs);
}
标准库提供的复数类是一个模板。
template<class T>
class complex{
public:
complex(T re,T im);
//......
};