CSC112 Spring 2016 Examples
#include <iostream>12using namespace std;34class Point {5public:6//overloaded constructors!7Point()8{9_x = 0;10_y = 0;11}1213Point(double _x, double _y)14{15this->_x = _x;16this->_y = _y;17}1819//overloaded methods for accessing x and y20double x()21{22return _x;23}2425void x(double val)26{27this->_x = val;28}2930double y()31{32return _y;33}3435void y(double val)36{37this->_y = val;38}39private:40//private attributes of the class41double _x;42double _y;43};444546//overload + operator for points47Point operator+(Point & lhs, Point & rhs);4849//an insertion operator for points50ostream & operator<<(ostream &os, Point &rhs);5152int main()53{54Point* p1 = new Point(2, 3);55Point* p2 = new Point(29.2, 17.4);56Point* p3 = new Point;5758//add the points together59*p3 = *p1 + *p2;6061cout << *p1 << " + " << *p2 << "=" << *p3 << endl;6263return 0;64}656667Point68operator+(Point &lhs, Point &rhs)69{70//make a new point71Point result;7273//set the component wise addition74result.x(lhs.x() + rhs.x());75result.y(lhs.x() + rhs.y());7677return result;78}798081ostream &82operator<<(ostream &os, Point &rhs)83{84//write to the stream85os << "(" << rhs.x() << ", " << rhs.y() << ")";8687//return the stream88return os;89}909192