#ifndef COMPLEX_H_INCLUDED #define COMPLEX_H_INCLUDED #include // Do NOT put “using namespace std” here--that’s namespace pollution! class Complex { public: Complex(double real = 0.0, double imag = 0.0); Complex(const Complex &); // Note lack of arg name ~Complex(); Complex& operator=(const Complex &); double real() const; // return real part double imag() const; // return imaginary part Complex conj() const; // return complex conjugate, a-bi double abs() const; // return sqrt(real²+imag²). static int get_count(); // return number of existing Complex objects Complex& operator+=(const Complex &); // add to this object Complex& operator-=(const Complex &); // subtract from this object Complex& operator*=(const Complex &); // multiply by this object Complex& operator/=(const Complex &); // divide by this object Complex& operator++(); // Prefix // real = real+1 Complex operator++(int); // Postfix // real = real+1 Complex& operator--(); // Prefix // imag = imag+1 Complex operator--(int); // Postfix // imag = imag+1 private: double re, im; // real & imaginary parts of the complex number // Assume that computing the absolute value of the complex number // is very expensive, so we cache the result. mutable double absolute_value; // Negative value means it's invalid. void invalidate_absolute_value(); // This marks it as invalid. // Keep track of how many instances of this class exist. // This is NOT required for all classes. It’s an academic example. static inline int count = 0; // number of existing objects }; // These functions are NOT methods, so we can do 3+c, where c is a Complex. // They’re marked [[nodiscard]] because if you go to the bother of adding // two complex numbers, you really should do something with the result. [[nodiscard]] Complex operator+(const Complex &, const Complex &); [[nodiscard]] Complex operator-(const Complex &, const Complex &); [[nodiscard]] Complex operator*(const Complex &, const Complex &); [[nodiscard]] Complex operator/(const Complex &, const Complex &); // Similarly, not methods, so we can do 3==c, where c is a Complex. bool operator==(const Complex &, const Complex &); bool operator!=(const Complex &, const Complex &); std::ostream& operator<<(std::ostream &, const Complex &); std::istream& operator>>(std::istream &, Complex &); #endif /* COMPLEX_H_INCLUDED */