fork download
  1. /* create a complex class with private members for the real and imaginary parts
  2. overload the +,-,and * operators to perform addition ,subtraction and multiplication
  3. of complex numbers. test the overloaded operators by creating two complex objects and
  4. performing arithmetic operations on them*/
  5. #include <iostream>
  6. using namespace std;
  7.  
  8. class Complex {
  9. private:
  10. float real;
  11. float imag;
  12.  
  13. public:
  14. // Constructor
  15. Complex(float r = 0, float i = 0) {
  16. real = r;
  17. imag = i;
  18. }
  19.  
  20. // Input method
  21. void input() {
  22. cout << "Enter real part: ";
  23. cin >> real;
  24. cout << "Enter imaginary part: ";
  25. cin >> imag;
  26. }
  27.  
  28. // Overload +
  29. Complex operator + (const Complex& c) const {
  30. return Complex(real + c.real, imag + c.imag);
  31. }
  32.  
  33. // Overload -
  34. Complex operator - (const Complex& c) const {
  35. return Complex(real - c.real, imag - c.imag);
  36. }
  37.  
  38. // Overload *
  39. Complex operator * (const Complex& c) const {
  40. float r = (real * c.real) - (imag * c.imag);
  41. float i = (real * c.imag) + (imag * c.real);
  42. return Complex(r, i);
  43. }
  44.  
  45. // Display method
  46. void display() const {
  47. cout << real;
  48. if (imag >= 0)
  49. cout << " + " << imag << "i" << endl;
  50. else
  51. cout << " - " << -imag << "i" << endl;
  52. }
  53. };
  54.  
  55. int main() {
  56. Complex c1, c2;
  57.  
  58. cout << "Enter first complex number:\n";
  59. c1.input();
  60.  
  61. cout << "\nEnter second complex number:\n";
  62. c2.input();
  63.  
  64. Complex sum = c1 + c2;
  65. Complex diff = c1 - c2;
  66. Complex prod = c1 * c2;
  67.  
  68. cout << "\nFirst Complex Number: ";
  69. c1.display();
  70.  
  71. cout << "Second Complex Number: ";
  72. c2.display();
  73.  
  74. cout << "\nSum: ";
  75. sum.display();
  76.  
  77. cout << "Difference: ";
  78. diff.display();
  79.  
  80. cout << "Product: ";
  81. prod.display();
  82.  
  83. return 0;
  84. }
  85.  
  86.  
  87.  
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
Enter first complex number:
Enter real part: Enter imaginary part: 
Enter second complex number:
Enter real part: Enter imaginary part: 
First Complex Number: 0 + 0i
Second Complex Number: 0 + 0i

Sum: 0 + 0i
Difference: 0 + 0i
Product: 0 + 0i