Write a C++ program to overload '+' operator using member function to add two complex numbers.
Q.) Write a C++ program to overload '+' operator using member function to add two complex numbers.
Subject: object oriented programming#include
#include
using namespace std;
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 operator+(const Complex& other) {
Complex result;
result.real = real + other.real;
result.imag = imag + other.imag;
return result;
}
void print() {
cout << "(" << real << ", " << imag << "i" << ")" << endl;
}
};
int main() {
Complex c1(3.0, 4.0);
Complex c2(5.0, -2.0);
Complex c3 = c1 + c2;
cout << "c1 = ";
c1.print();
cout << "c2 = ";
c2.print();
cout << "c3 = c1 + c2 = ";
c3.print();
return 0;
}
Explanation:
We define a
Complex
class to represent complex numbers. It has two private data members,real
andimag
, to store the real and imaginary parts of the complex number, respectively.We define a constructor that takes two double parameters,
r
andi
, and initializes thereal
andimag
data members with these values.We define an overloaded
+
operator using themember function
syntax. This operator takes aconst Complex&
parameterother
and returns aComplex
object. Inside the operator function, we calculate the sum of the real and imaginary parts of the two complex numbers and store the result in a newComplex
object, which we return as the result.We define a
print()
member function in theComplex
class to print the complex number in the format(real, imag i)
.In the
main()
function, we create twoComplex
objects,c1
andc2
, with the values (3.0, 4.0) and (5.0, -2.0), respectively.We create a third
Complex
object,c3
, by addingc1
andc2
using the overloaded+
operator.We print the values of
c1
,c2
, andc3
using theprint()
member function.
When we run this program, it will output the following:
c1 = (3, 4i)
c2 = (5, -2i)
c3 = c1 + c2 = (8, 2i)
This shows that the +
operator has been successfully overloaded to add two complex numbers.