Objective: Write a C++ program to overload binary operator `+' to add two complex numbers.
Code:
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor to initialize complex number
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Overloading the '+' operator to add two Complex numbers
Complex operator + (const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
// Function to display the complex number
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
// Creating two Complex objects
Complex c1(3.4, 5.6);
Complex c2(1.2, 3.8);
// Adding two complex numbers using the overloaded '+' operator
Complex c3 = c1 + c2;
// Displaying the result
cout << "Complex number 1: ";
c1.display();
cout << "Complex number 2: ";
c2.display();
cout << "Sum of Complex numbers: ";
c3.display();
return 0;
}
Output:
No comments:
Post a Comment