Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

CSC112 Spring 2016 Examples

2370 views
1
#include <iostream>
2
3
using namespace std;
4
5
class Point {
6
public:
7
//overloaded constructors!
8
Point()
9
{
10
_x = 0;
11
_y = 0;
12
}
13
14
Point(double _x, double _y)
15
{
16
this->_x = _x;
17
this->_y = _y;
18
}
19
20
//overloaded methods for accessing x and y
21
double x()
22
{
23
return _x;
24
}
25
26
void x(double val)
27
{
28
this->_x = val;
29
}
30
31
double y()
32
{
33
return _y;
34
}
35
36
void y(double val)
37
{
38
this->_y = val;
39
}
40
private:
41
//private attributes of the class
42
double _x;
43
double _y;
44
};
45
46
47
//overload + operator for points
48
Point operator+(Point & lhs, Point & rhs);
49
50
//an insertion operator for points
51
ostream & operator<<(ostream &os, Point &rhs);
52
53
int main()
54
{
55
Point* p1 = new Point(2, 3);
56
Point* p2 = new Point(29.2, 17.4);
57
Point* p3 = new Point;
58
59
//add the points together
60
*p3 = *p1 + *p2;
61
62
cout << *p1 << " + " << *p2 << "=" << *p3 << endl;
63
64
return 0;
65
}
66
67
68
Point
69
operator+(Point &lhs, Point &rhs)
70
{
71
//make a new point
72
Point result;
73
74
//set the component wise addition
75
result.x(lhs.x() + rhs.x());
76
result.y(lhs.x() + rhs.y());
77
78
return result;
79
}
80
81
82
ostream &
83
operator<<(ostream &os, Point &rhs)
84
{
85
//write to the stream
86
os << "(" << rhs.x() << ", " << rhs.y() << ")";
87
88
//return the stream
89
return os;
90
}
91
92