C++ code


SUBMITTED BY: DylanLaplante

DATE: Oct. 29, 2020, 9:46 p.m.

FORMAT: Text only

SIZE: 1.2 kB

HITS: 493

  1. #include <iostream>
  2. using namespace std;
  3. class Complex
  4. {
  5. private:
  6. float real;
  7. float imag;
  8. public:
  9. Complex(): real(0), imag(0){ }
  10. void input()
  11. {
  12. cout << "Enter real and imaginary parts respectively: ";
  13. cin >> real;
  14. cin >> imag;
  15. }
  16. // Operator overloading
  17. Complex operator - (Complex c2)
  18. {
  19. Complex temp;
  20. temp.real = real - c2.real;
  21. temp.imag = imag - c2.imag;
  22. return temp;
  23. }
  24. void output()
  25. {
  26. if(imag < 0)
  27. cout << "Output Complex number: "<< real << imag << "i";
  28. else
  29. cout << "Output Complex number: " << real << "+" << imag << "i";
  30. }
  31. };
  32. int main()
  33. {
  34. Complex c1, c2, result;
  35. cout<<"Enter first complex number:\n";
  36. c1.input();
  37. cout<<"Enter second complex number:\n";
  38. c2.input();
  39. // In case of operator overloading of binary operators in C++ programming,
  40. // the object on right hand side of operator is always assumed as argument by compiler.
  41. result = c1 - c2;
  42. result.output();
  43. return 0;
  44. }

comments powered by Disqus