Question: Modify the Complex.h and Complex.cpp to support operator overloading for the operators +, -, *, and / for add, sub, mul, and div operations. Demonstrate
Modify the Complex.h and Complex.cpp to support operator overloading for the operators +, -, *, and / for add, sub, mul, and div operations. Demonstrate overloaded operators in the Application.cpp.
Complex.cpp
#include
using namespace std;
#include "Complex.h"
Complex Complex::add(const Complex &c) const {
Complex result;
result.real = real + c.real;
result.imag = imag + c.imag;
return result;
}
Complex Complex::sub(const Complex &c) const {
Complex result;
result.real = real - c.real;
result.imag = imag - c.imag;
return result;
}
Complex Complex::mul(const Complex &c) const {
Complex result;
result.real = real * c.real - imag * c.imag;
result.imag = imag * c.real + real * c.imag;
return result;
}
Complex Complex::div(const Complex &c) const {
double t = c.real * c.real + c.imag * c.imag;
Complex result;
result.real = (real * c.real + imag * c.imag) / t;
result.imag = (imag * c.real - real * c.imag) / t;
return result;
}
void Complex::print() const {
cout << "( " << real << ", " << imag << " ) ";
}
Complex.h
#pragma once
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
private:
double real;
double imag;
public:
Complex() : real(0.0), imag(0.0) {}
Complex(double r, double i) : real(r), imag(i) {}
Complex(const Complex &c) : real(c.real), imag(c.imag) {}
// above statement must be pass-by-reference so that the default copy constructor is not used.
// if it is pass-by-value, the above statement is not a copy constructor and function
// overloading occurs the compiler cannot resolve
void setReal(double r) { real = r; }
void setImag(double i) { imag = i; }
void setComplex(Complex c) { real = c.real; imag = c.imag; }
double getReal() { return real; }
double getImag() { return imag; }
Complex add(const Complex &) const;
Complex sub(const Complex &) const;
Complex mul(const Complex &) const;
Complex div(const Complex &) const;
void print() const;
};
#endif
Application.cpp
#include
#include "Complex.h"
using namespace std;
void main()
{
Complex a(4.0, 6.0), b(3.0, 5.0), *c = new Complex;
Complex d(a); d.print();
a.add(b).print();
c.print();
c = b - a;
c.print();
c = a*b;
c.print();
c = a / b;
c.print();
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
To implement operator overloading for the operators and for the Complex class youll need to modify the Complexh and Complexcpp files The main goal is ... View full answer
Get step-by-step solutions from verified subject matter experts
