面向对象复数类(class Complex) 的重载运算符 一元二元的实现与使用



面向对象复数类(class Complex)


一.

     实现与测试使用总共分为两个部分_(:зゝ∠)_,头文件与主函数 ,重载操作符与类成员函数有注释声明

      唯一的注意点在于一元加法操作符返回的是类引用 而二元加法操作符返回的是类对象

      其中二元加法操作符重载了三种参数情况

      运算部分用到了友元函数

      主函数测试部分自行按需要去掉注释

      仅供参考,随意浏览_(:зゝ∠)_

      近期补完完整版复数类 重载运算符与成员函数

头文件实现部分:

#ifndef _Complex_
#define _Complex_

#include 
#include 
using namespace std;
#include 

#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 += 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 
#include 
#include 
using namespace std;
#include "Complex.h"

int main ()
{
	// references
	Complex c1(2,1);
	cout<<"Put c1"<




你可能感兴趣的:(面向对象,类)