Vserosbuybuy

Complex class, C++

Mar 16th, 2021 (edited)
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. class Complex {
  7. private:
  8.     double re;
  9.     double im;
  10. public:
  11.     Complex(double _re, double _im = 0) : re(_re), im(_im) {}
  12.  
  13.     double Re() const {
  14.         return re;
  15.     }
  16.  
  17.     double Im() const {
  18.         return im;
  19.     }
  20.  
  21.     const Complex& operator+ () const {
  22.         return *this;
  23.     }
  24.  
  25.     Complex operator- () const {
  26.         return Complex(-re, -im);
  27.     }
  28.  
  29.     friend Complex operator+(const Complex& a, const Complex& b);
  30.     friend Complex operator-(const Complex& a, const Complex& b);
  31.     friend Complex operator*(const Complex& a, const Complex& b);
  32.     friend Complex operator/(const Complex& a, const Complex& b);
  33.     friend bool operator==(const Complex& a, const Complex& b);
  34.     friend bool operator!=(const Complex& a, const Complex& b);
  35. };
  36.  
  37. Complex operator+(const Complex& a, const Complex& b) {
  38.     return Complex(a.re + b.re, a.im + b.im);
  39. }
  40.  
  41. Complex operator-(const Complex& a, const Complex& b) {
  42.     return Complex(a.re - b.re, a.im - b.im);
  43. }
  44.  
  45. Complex operator*(const Complex& a, const Complex& b) {
  46.     return Complex(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);
  47. }
  48.  
  49. Complex operator/(const Complex& a, const Complex& b) {
  50.     double re = (a.re * b.re + a.im * b.im) / (b.re * b.re + b.im * b.im);
  51.     double im = (b.re * a.im - b.im * a.re) / (b.re * b.re + b.im * b.im);
  52.     return Complex(re, im);
  53. }
  54.  
  55. bool operator==(const Complex& a, const Complex& b) {
  56.     if (a.re == b.re && a.im == b.im) {
  57.         return true;
  58.     }
  59.     else {
  60.         return false;
  61.     }
  62. }
  63.  
  64. bool operator!=(const Complex& a, const Complex& b) {
  65.     return !(a == b);
  66. }
  67.  
  68. double abs(const Complex& a) {
  69.     return sqrt(a.Re() * a.Re() + a.Im() * a.Im());
  70. }
Advertisement
Add Comment
Please, Sign In to add comment