Overloading Binary Operators using friend function By Dr
Overloading Binary Operators using friend function By: Dr. Piyush Kumar Singh Dept. of Computer Science Central University of South Bihar
Invoking Overload Binary Operators using friend function If x and y are two operand op is operator then it can be invoked by general syntax operator op (x, y)
Overloading Binary Operator + for addition of two complex numbers (Class Definition): # include<iostraem> using namespace std; class complex { float x; float y; public: complex (){} // Constructor 1 Definition
Overloading Binary Operator + for addition of two complex numbers (Class Definition): complex (float real, float img) // constructor 2 definition { x=real; y= img; } friend complex operator+(complex, complex); void display(); }; // End of Class definition
Overloading Binary Operator + for addition of two complex numbers (Operator definition): complex operator+(complex a, complex b) { complex temp; temp. x = a. x + b. x; temp. y = a. y + b. y; return (temp); }
Overloading Binary Operator + for addition of two complex numbers (display function definition): void complex : : display() { cout << x <<“+j” << y << “nn”; }
Overloading Binary Operator + for addition of two complex numbers (main function definition): int main () { complex C 1, C 2, C 3; C 1 = complex(2. 5, 3. 5); C 2 = complex(1. 6, 2. 7); C 3 = operator+(C 1, C 2); cout << “C 1 = ”; C 1. display(); cout << “C 2 = ”; C 2. display(); cout << “C 3 = ”; C 3. display(); return 0; }
Overloading Binary Operator + for addition of two complex numbers (OUTPUT): C 1 = 2. 5 + j 3. 5 C 2 = 1. 6 + j 2. 7 C 3 = 4. 1 + j 6. 2
References: 1. Object Oriented Programming with C++, 3/e by E. Balagurusamy, Tata Mc. Graw Hill. 2. Mastering C++, 1/e by Venugopal, Tata Mc. Graw Hill.
Thank You
- Slides: 10