Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 復數類的運算符重載實作

本文實作了一個復數類,並重載了各類運算符。網上較少見到的 cout、cin 重載,以及乘法 *、除法 /,這裡一併完成。先看宣告:

Complex.h:
#ifndef __COMPLEX__
#define __COMPLEX__
#include <iostream>
using namespace std;
class Complex
{
public:
  friend ostream & operator << (ostream& out, const Complex& num)
  {
    if (num._imgic<0.0)
      out << num._real << " - " << -(num._imgic) << "i";
    else
      out << num._real << " + " << num._imgic << "i";
    return out;
  }
  friend istream & operator>> (istream& in, Complex& num)
  {
    in >> num._real;
    in >> num._imgic;
    return in;
  }
  Complex(double real = 0, double imgic = 0) :_real(real), _imgic(imgic) {}
  ~Complex() {}
  bool operator >(const Complex & num);
  bool operator <(const Complex & num);
  bool operator ==(const Complex & num);
  bool operator >=(const Complex & num);
  bool operator <=(const Complex & num);
  bool operator !=(const Complex & num);
  Complex operator + (const Complex & num);
  Complex operator - (const Complex & num);
  Complex operator ++ ();
  Complex operator ++ (int);
  Complex operator -- ();
  Complex operator -- (int);
  Complex operator += (const Complex & num);
  Complex operator -= (const Complex & num);
  Complex operator * (const Complex & num);
  Complex operator *= (const Complex & num);
  Complex operator /  (Complex & num);
  Complex operator /= (Complex & num);
  Complex operator ~ ();
private:
  double _real;
  double _imgic;
};
#endif

實作部分如下。特別說明幾個重點:比較運算依據模長(實部平方加虛部平方)來判定大小;++/-- 這裡只對實部增減;而除法之所以要先實作 ~(共軛),是因為復數相除需分子分母同乘分母的共軛:

#include "Complex.h"
bool Complex::operator >(const Complex & num)
{
  if ((_real*_real + _imgic*_imgic) > (num._real*num._real + num._imgic*num._imgic)) return true;
  return false;
}
bool Complex::operator ==(const Complex & num)
{
  return (_real == num._real) && (_imgic == num._imgic);
}
Complex Complex::operator + (const Complex & num)
{
  return Complex(_real + num._real, _imgic + num._imgic);
}
Complex Complex::operator - (const Complex & num)
{
  return Complex(_real - num._real, _imgic - num._imgic);
}
Complex Complex::operator * (const Complex & num)
{
  return Complex((_real*num._real - _imgic*num._imgic), (_real*num._imgic + (num._imgic*_real)));
}
Complex Complex::operator / (Complex & num)
{
  return Complex(((*this*(~num))._real) / ((num*(~num))._real), ((*this*(~num))._imgic) / ((num*(~num))._real));
}
Complex Complex::operator ~ ()
{
  return Complex(_real, -_imgic);
}

透過把 << 與 >> 宣告為友元,就能像操作內建型別一樣直接輸入輸出復數,程式碼可讀性大大提升。如有不足,歡迎留言一起探討。

Copyright © Linux教程網 All Rights Reserved