Answer to Question #174811 in C++ for Anu

Question #174811

Define a class complex with for real and imaginary part of two complex numbers, write a constructor function to initialize objects and display the real and imaginary parts.


1
Expert's answer
2021-03-23T13:19:55-0400
#include <iostream>
#include <cmath>

using namespace std;

class Complex {
    private:
        double real;
        double imaginary;
    public:
        Complex(double real=0, double imaginary=0);
        ~Complex();

        double getReal() const;
        double getImaginary() const;
};

std::ostream& operator<<(std::ostream& out, const Complex& complex);


Complex::Complex(double real, double imaginary) {
    this->real = real;
    this->imaginary = imaginary;
}

Complex::~Complex() {
    
}

double Complex::getReal() const {
    return this->real;
}

double Complex::getImaginary() const {
    return this->imaginary;
}

std::ostream& operator<<(std::ostream& out, const Complex& other) {
    return out << other.getReal() << "+" << other.getImaginary() << "i";
}

int main() {
    Complex z1(5, 6);
    Complex z2(3, 2);

    cout << "Complex number z1 is: " << z1 << "\n";
    cout << "Complex number z2 is: " << z2 << "\n";

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS