C++ examples for Class:Operator Overload
Overload the cast operator from custom class to int
#include <iostream> using namespace std; class Box {/* w w w .j a v a 2s.com*/ 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; } // A conversion to int. operator int() { return x + y + z; } // Let the overloaded inserter be a friend. friend ostream &operator<<(ostream &strm, Box op); }; // 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; } // Return the negation of v. int neg(int v) { return -v; } // Return true if x is less than y. bool lt(int x, int y) { if(x < y) return true; return false; } int main() { Box objA(1, 2, 3), objB(-1, -2, -3); int result; cout << "Value of objA: " << objA; cout << "Value of objB: " << objB; cout << endl; // Use objA in an int expression. cout << "Use a Box object in an int expression: "; result = 10 + objA; cout << "10 + objA: " << result << "\n\n"; // Pass objA to a function that takes an int argument. cout << "Pass a Box object to an int parameter: "; result = neg(objA); cout << "neg(objA): " << result << "\n\n"; cout << "Compare the sum of the coordinates by use of lt(): "; if(lt(objA, objB)) cout << "objA less than objB\n"; else if(lt(objB, objA)) cout << "objB less than objA\n"; else cout << "objA and objB both sum to the same value.\n"; return 0; }