fork download
  1. // CPP program to illustrate
  2. // Operator Overloading
  3. #include<iostream>
  4. using namespace std;
  5.  
  6. class Complex {
  7. private:
  8. int real, imag;
  9. public:
  10. Complex(int r = 0, int i =0) {real = r; imag = i;}
  11.  
  12. // This is automatically called when '+' is used with
  13. // between two Complex objects
  14. Complex operator + (Complex const &obj) {
  15. Complex res;
  16. res.real = real + obj.real;
  17. res.imag = imag + obj.imag;
  18. return res;
  19. }
  20. void print() { cout << real << " + i" << imag << endl; }
  21. };
  22.  
  23. int main()
  24. {
  25. Complex c1(10, 5), c2(2, 4);
  26. Complex c3 = c1 + c2; // An example call to "operator+"
  27. c3.print();
  28. }
  29.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
12 + i9