
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Overload Addition Operator to Add Two Complex Numbers in C++
Suppose we have a complex number class with real and imaginary part. We shall have to overload the addition (+) operator to add two complex number. We also have to define a function to return complex number in proper representation.
So, if the input is like c1 = 8 - 5i, c2 = 2 + 3i, then the output will be 10 - 2i.
To solve this, we will follow these steps −
Overload the + operator and take another complex number c2 as argument
define a complex number called ret whose real and imag are 0
real of ret := own real + real of c2
imag of ret := own imag + imag of c2
return ret
Example
Let us see the following implementation to get better understanding −
#include <iostream> #include <sstream> #include <cmath> using namespace std; class Complex { private: int real, imag; public: Complex(){ real = imag = 0; } Complex (int r, int i){ real = r; imag = i; } string to_string(){ stringstream ss; if(imag >= 0) ss << "(" << real << " + " << imag << "i)"; else ss << "(" << real << " - " << abs(imag) << "i)"; return ss.str(); } Complex operator+(Complex c2){ Complex ret; ret.real = real + c2.real; ret.imag = imag + c2.imag; return ret; } }; int main(){ Complex c1(8,-5), c2(2,3); Complex res = c1 + c2; cout << res.to_string(); }
Input
c1(8,-5), c2(2,3)
Output
(10 - 2i)
Advertisements