面向对象复数类(class Complex)
一.
实现与测试使用总共分为两个部分_(:зゝ∠)_,头文件与主函数 ,重载操作符与类成员函数有注释声明
唯一的注意点在于一元加法操作符返回的是类引用 而二元加法操作符返回的是类对象
其中二元加法操作符重载了三种参数情况
运算部分用到了友元函数
主函数测试部分自行按需要去掉注释
仅供参考,随意浏览_(:зゝ∠)_
近期补完完整版复数类 重载运算符与成员函数
头文件实现部分:
#ifndef _Complex_
#define _Complex_
#include <cmath>
#include <iostream>
using namespace std;
#include <cstring>
#endif//_Complex_
class Complex;
Complex& _doapl (Complex *,Complex&);
Complex& _doapl (Complex *,Complex&);
class Complex {
public:
Complex (double tr=0,double ti=0)
{
re=tr;
im=ti;
}
Complex& operator *= ( const Complex &);
Complex& operator += ( const Complex &);
void Put () {cout<<re<<"+"<<im<<"i"<<endl;}
void Set (double ,double);
double real() const { return re;}
double imag() const { return im;}
~Complex()
{
cout<<"Destroying class Complex"<<endl;
}
private:
double re;
double im;
friend Complex& _doapl (Complex*,const Complex& r );
friend Complex& _doamu (Complex*,const Complex& r );
};
// Set
inline void
Complex::Set(double tr,double ti)
{
re=tr;
im=ti;
}
// friend function
inline Complex&
_doapl (Complex* ths, const Complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
inline Complex&
_doamu (Complex* ths, const Complex& r)
{
Complex* t;
t=new Complex;
t->re=ths->re;
t->im=ths->im;
ths->re=t->re*r.re - t->im*r.im;
ths->im=t->im*r.re + t->re*r.im;
delete t;
return *ths;
}
// operator += *=
inline Complex&
Complex::operator += (const Complex& r)
{
return _doapl (this, r);
}
inline Complex&
Complex::operator *= (const Complex& r)
{
return _doamu (this ,r);
}
// return re,im;
inline double
imag (const Complex& x)
{
return x.imag ();
}
inline double
real (const Complex& x)
{
return x.real ();
}
// Plus 3 mode
inline Complex
operator + (const Complex& x, const Complex& y)
{
return Complex (real (x) + real (y), imag (x) + imag (y));
}
inline Complex
operator + (const Complex& x, double y)
{
return Complex (real (x) + y, imag (x));
}
inline Complex
operator + (double x, const Complex& y)
{
return Complex (x + real (y), imag (y));
}
主函数测试部分:
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
#include "Complex.h"
int main ()
{
// references
Complex c1(2,1);
cout<<"Put c1"<<endl;
c1.Put();
cout<<endl;
Complex c2(4,3);
cout<<"Put c2"<<endl;
c2.Put();
cout<<endl;
Complex c3;
cout<<"Put c3"<<endl;
c3.Put();
cout<<endl;
/*
//Function set
cout<<"after Set , Put c1"<<endl;
c1.Set(3,2);
c1.Put();
*/
/*
c1+=c2;
cout<<"after Plu , c1"<<endl;
c1.Put();
cout<<endl;
*/
//operator *=
/*
c1*=c2;
cout<<"after Mut, c1"<<endl;
c1.Put();
cout<<endl;
*/
/*
//operator Plus c+c
cout<<"c1+c2=";
(c1+c2).Put();
cout<<endl;
//operator Plus c+r
cout<<"c1+2=";
(c1+2).Put();
cout<<endl;
//operatro Plus r+c
cout<<"3+c1=";
(3+c1).Put();
cout<<endl;
*/
system("pause");
return 0;
}