Complex Numbers header file

 Save this as complex.h

-------------------------------------------------------------------------------------------------


 
#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>

class Complex {
private:
    double x, y;

public:
    // Constructor with default values
    explicit Complex(double xval = 0.0, double yval = 0.0) : x(xval), y(yval) {}

    // Getters
    double real() const { return x; }
    double imag() const { return y; }

    // Setters
    void setReal(double x_new) { x = x_new; }
    void setImag(double y_new) { y = y_new; }

    // Overloaded operators as friend functions
    friend Complex operator+(const Complex& p, const Complex& q);
    friend Complex operator-(const Complex& p, const Complex& q);
    friend Complex operator*(const Complex& p, const Complex& q);
    friend Complex operator/(const Complex& p, const Complex& q);
    friend std::ostream& operator<<(std::ostream& os, const Complex& c);
};

// Operator Overloads
Complex operator+(const Complex& p, const Complex& q) {
    return Complex(p.x + q.x, p.y + q.y);
}

Complex operator-(const Complex& p, const Complex& q) {
    return Complex(p.x - q.x, p.y - q.y);
}

Complex operator*(const Complex& p, const Complex& q) {
    return Complex(p.x * q.x - p.y * q.y, p.x * q.y + p.y * q.x);
}

Complex operator/(const Complex& p, const Complex& q) {
    return Complex((p.x * q.x + p.y * q.y) / (q.x * q.x + q.y * q.y), (p.y * q.x - p.x * q.y) / (q.x * q.x + q.y * q.y));
}

// Overloaded << operator for easy printing
std::ostream& operator<<(std::ostream& os, const Complex& c) {
    os << c.x;
    if (c.y > 0) os << " + " << c.y << "i";
    else if (c.y < 0) os << " - " << -c.y << "i";
    return os;
}

#endif // COMPLEX_H

 
----------------------------------------
Now import this in another file

 
#include "complex.h"
#include <iostream>
int main() {
    Complex p(3,4);
    Complex q(3.4, 4.3);
    Complex r = p / q;
    std::cout << r;
    return 0;
}
 


Comments