C++ examples for Class:Operator Overload
Overload inserter and extractor to output the coordinates and read the coordinates.
#include <iostream> using namespace std; class Box {//from w w w. jav a 2s . com int x, y, z; // 3-D coordinates public: Box(int a, int b, int c) { x = a; y = b; z = c; } // Make the inserter and extractor friends of Box. friend ostream &operator<<(ostream &stream, const Box &obj); friend istream &operator>>(istream &stream, Box &obj); // ... }; // Box inserter. Display the X, Y, Z coordinates. ostream &operator<<(ostream &stream, const Box &obj) { stream << obj.x << ", "; stream << obj.y << ", "; stream << obj.z << "\n"; return stream; // return the stream } // Box extractor. Get three-dimensional values. istream &operator>>(istream &stream, Box &obj) { stream >> obj.x >> obj.y >> obj.z; return stream; } int main() { Box td(1, 2, 3); cout << "The coordinates in td: " << td << endl; cout << "Enter new three-d coordinates: "; cin >> td; cout << "The coordinates in td are now: " << td << endl; return 0; }