fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Complex
  5. {
  6. private:
  7. float real;
  8. float imag;
  9. public:
  10. Complex():
  11. real(0), imag(0){ }
  12. void input()
  13. {
  14. cout << "Enter real and imaginary parts respectively: "<<endl;
  15. cin >> real;
  16. cin >> imag;
  17. }
  18.  
  19. // Operator overloading
  20. Complex operator + (Complex c)
  21. {
  22. Complex temp;
  23. temp.real = real + c.real;
  24. temp.imag = imag + c.imag;
  25.  
  26. return temp;
  27. }
  28.  
  29. Complex operator - (Complex c)
  30. {
  31. Complex temp;
  32. temp.real=real-c.real;
  33. temp.imag=imag-c.imag;
  34.  
  35. return temp;
  36. }
  37.  
  38. void output()
  39. {
  40. if(imag < 0)
  41. cout << "Output Complex number: "<< real << imag << "i"<<endl;
  42. else
  43. cout << "Output Complex number: " << real << "+" << imag << "i"<<endl;
  44. }
  45. };
  46.  
  47. int main()
  48. {
  49. Complex c1, c2, result,resultt;
  50. c1.input();
  51. c2.input();
  52.  
  53. // In case of operator overloading of binary operators in C++ programming,
  54. // the object on right hand side of operator is always assumed as argument by compiler.
  55. result = c1 + c2;
  56. result.output();
  57. resultt = c1 - c2;
  58. resultt.output();
  59. return 0;
  60. }
Success #stdin #stdout 0.01s 5516KB
stdin
9
7
7
9
stdout
Enter real and imaginary parts respectively: 
Enter real and imaginary parts respectively: 
Output Complex number: 16+16i
Output Complex number: 2-2i