pgrm_018.cpp (1069B)
1 /* Operator overloading */ 2 3 #include<iostream> 4 using namespace std; 5 class complex { 6 private: 7 int real; 8 int img; 9 public: 10 complex(float r = 0, float i = 0) { 11 real = r; img = i; 12 } 13 14 // overloading the `+` operator 15 complex operator +(const complex &obj) { 16 complex temp; 17 temp.real = real + obj.real; 18 temp.img = img + obj.img; 19 return temp; 20 } 21 22 complex add_complex(const complex &obj) { 23 complex temp; 24 temp.real = real + obj.real; 25 temp.img = img + obj.img; 26 return temp; 27 } 28 29 void output() { 30 cout << "Complex number: " << real << "+" << img << "i" << endl; 31 } 32 }; 33 34 int main() { 35 complex complex1(10, 20), complex2(20, 30), result; 36 cout << "First complex number: "; 37 complex1.output(); 38 cout << "Second complex number: "; 39 complex2.output(); 40 cout << "After addition: "; 41 result = complex1 + complex2; 42 result.output(); 43 cout << "After addition: "; 44 result = complex1.add_complex(complex2); 45 result.output(); 46 return 0; 47 }