C++ examples for Class:Operator Overload
Demonstrate the function call operator.
#include <iostream> using namespace std; class Box {//from w ww . j a va 2 s.c o m int x, y, z; // 3-D coordinates public: Box() { x = y = z = 0; } Box(int i, int j, int k) { x = i; y = j; z = k; } // Create two function call operator functions. Box operator()(Box obj); Box operator()(int a, int b, int c); // Let the overloaded inserter be a friend. friend ostream &operator<<(ostream &strm, Box op); }; // Overload function call. // returns a Box object whose coordinates are the midpoints between the invoking object and obj. Box Box::operator()(Box obj) { Box temp; temp.x = (x + obj.x) / 2; temp.y = (y + obj.y) / 2; temp.z = (z + obj.z) / 2; return temp; } // Overload function call. Take three ints as parameters. This version adds the arguments to the coordinates. Box Box::operator()(int a, int b, int c) { Box temp; temp.x = x + a; temp.y = y + b; temp.z = z + c; return temp; } // The Box inserter is a non-member operator function. ostream &operator<<(ostream &strm, Box op) { strm << op.x << ", " << op.y << ", " << op.z << endl; return strm; } int main() { Box objA(1, 2, 3), objB(10, 10, 10), objC; cout << "This is objA: " << objA; cout << "This is objB: " << objB; objC = objA(objB); cout << "objA(objB): " << objC; objC = objA(10, 20, 30); cout << "objA(10, 20, 30): " << objC; // Can use the result of one as an argument to another. objC = objA(objB(100, 200, 300)); cout << "objA(objB(100, 200, 300)): " << objC; return 0; }