tampurus

10.1 operator overloading ( insertion<< )

Dec 22nd, 2021 (edited)
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. // insertion operator overloading
  2.  
  3. // normal way to display the data members of object
  4. #include <iostream>
  5. using namespace std;
  6. class complex
  7. {
  8. private:
  9.     int real;
  10.     int img;
  11. public:
  12.     complex(int a=0 , int b=0 ){ // non parameterized constructor
  13.         real = a;
  14.         img = b;
  15.     }
  16.     void display(){
  17.         cout<<real<<" + i"<<img<<endl;
  18.     }
  19. };
  20. int main()
  21. {
  22.     complex c1(8,5);
  23.     c1.display();
  24.     return 0;
  25. }
  26.  
  27.  
  28.  
  29. // now with operator<< that is insertion operator overloading
  30.  
  31. #include <iostream>
  32. using namespace std;
  33. class complex
  34. {
  35. private:
  36.     int real;
  37.     int img;
  38. public:
  39.     complex(int a=0 , int b=0 ){ // non parameterized constructor, if no value passed default it will be zero
  40.         real = a;
  41.         img = b;
  42.     }
  43.     friend ostream & operator<<(ostream &suresh , complex &c);
  44. };
  45.  
  46. ostream & operator<<(ostream &suresh , complex &c)
  47. {
  48.     suresh<<c.real<<" + i"<<c.img<<endl;
  49. }
  50. int main()
  51. {
  52.     complex c(8,5);
  53.     cout<<c; // same as operator<<(cout,c);
  54.     return 0;
  55. }
  56.  
  57. /*
  58. 8 + i5
  59. */
Add Comment
Please, Sign In to add comment