Create Complex class to do arithmetic with complex numbers. - C++ Class

C++ examples for Class:Operator Overload

Description

Create Complex class to do arithmetic with complex numbers.

Demo Code

                                                                                                                                             
#include <iostream>
                                                                                                                                             
class Complex {/* w ww  . ja va 2  s .com*/
 public:
    explicit Complex(double = 1, double = 1);
    ~Complex();
                                                                                                                                             
    // overloaded operators
    Complex operator+(Complex c) const {
        return Complex(real + c.real, imaginary + c.imaginary);
    }
    Complex operator-(Complex c) const {
        return Complex(real - c.real, imaginary - c.imaginary);
    }
                                                                                                                                             
    friend std::ostream& operator<<(std::ostream& out, Complex& c) {
        return c.printComplex(out);
    }
                                                                                                                                             
 private:
    double real;
    double imaginary;
                                                                                                                                             
    std::ostream& printComplex(std::ostream&);
};
Complex::Complex(double r, double i) {
    real = r;
    imaginary = i;
}
Complex::~Complex() {}
                                                                                                                                             
// print complex number
std::ostream& Complex::printComplex(std::ostream& out) {
    return out << "(" << real << "," << imaginary << ")";
}
int main(int argc, const char *argv[]) {
    Complex c1;
    Complex c2(123, 456);
                                                                                                                                             
    Complex c3 = (c1 + c2);
                                                                                                                                             
    std::cout << "c1: " << c1 << "\nc2: " << c2 << "\nc3: " << c3 << std::endl;
                                                                                                                                             
    return 0;
}

Result


Related Tutorials