#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) : real(r), imag(i) {} // Constructor
// Overloading binary + operator
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag); }
void display() const {
cout << real << ” + ” << imag << “i” << endl; } };
int main() {
Complex c1(5, 3);
Complex c2(2, 7);
cout << “Complex numbers:\n”;
c1.display();
c2.display();
// Addition using overloaded + operator
Complex c3 = c1 + c2; // Same as c1.operator+(c2)
cout << “\nSum: “;
c3.display();
return 0; }
Output:
Complex numbers:
5 + 3i
2 + 7i
Sum: 7 + 10i
Here’s a step-by-step explanation of the code:
1. Headers and Namespace:
- #include <iostream>: Includes the iostream header for input/output operations.
- using namespace std;: Brings the std namespace into scope for convenient use of elements like cout, cin, and endl.
2. Complex Class:
- class Complex { … }: Defines a class named Complex to represent complex numbers.
- private: int real, imag;: Private member variables to store the real and imaginary parts.
- public: Complex(int r = 0, int i = 0) : real(r), imag(i) {}: Constructor to initialize complex numbers with optional values.
- Complex operator+(const Complex& other) const { … };: Overloads the binary + operator to add two complex numbers.
- void display() const { … };: Member function to display a complex number in the format “real + imag i”.
3. Main Function:
- int main() { … }: The program’s entry point.
- Complex c1(5, 3), c2(2, 7);: Creates two objects of the Complex class.
- cout << “Complex numbers:\n”; c1.display(); c2.display();: Prints the initial complex numbers.
- Complex c3 = c1 + c2;: Adds c1 and c2 using the overloaded + operator and stores the result in c3.
- cout << “\nSum: “; c3.display();: Prints the sum of the complex numbers.
- return 0;: Indicates successful program termination.
4. Operator Overloading Key Points:
- Operator Function Name: The overloaded + operator function is named operator+().
- Arguments: It takes a constant reference to another Complex object as its argument.
- Return Type: It returns a new Complex object representing the sum of the two complex numbers.
- Implementation: The function adds the real and imaginary parts separately and returns a new Complex object with the calculated values.