Add two points

Hello! I need to write a program to overload +,-,*,++, and - operators to add two points, subtract two points, multiply a point by a constant k, auto increment and auto decrement the coordinates of a point by one. I already have the distance of the two points but I am having trouble making the functions to add the two points. How would I do this? This is what I have so far. Thank you!

Sample I/O:
Enter the coordinates of point A: 2 3
Enter the coordinates of point B: 5 7
A(2,3) + B(5,7) = C(7,10)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <iomanip>
using namespace std;

class POINT
{private: int x,y;
public:
	void read (char vertex);

	friend void Display (POINT p, POINT q);
	
	friend float Distance (POINT p, POINT q);

	friend float Add (POINT p, POINT q);

	friend void Display (float AB);
};

	int main ()
	{
		POINT A,B;

		A.read('A'); B.read('B');

		float Sum = Add(A,B);

		cout <<fixed<< showpoint << setprecision(2);
		float AB=Distance(A,B);
		
		Display (A,B); Display(AB);
	
		system ("pause");
		return 0;
	}

	void POINT :: read(char vertex)
	{
		cout << "Enter the coordinates of point " << vertex << ": ";
		cin >> x >> y;
	}
	
	float Add (POINT p, POINT q)
	{
		return (p.x+q.x);
	}

	float Distance (POINT p, POINT q)
	{
		return sqrt(pow(p.x-q.x,2.)+pow(p.y-q.y,2.));
	}

	void Display (float AB)
	{
		cout << AB << endl;
	}
	
	void Display (POINT p, POINT q)
	{
		cout << "A(" << p.x << "," << p.y << ") + B(" << q.x << "," << q.y << ")= ";
		cout << "The distance from A(" << p.x << "," << p.y << ") to B(" << q.x << "," << q.y << ") is ";
	}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class POINT 
{
private :
    int x, y;
    
public :
    // ...
    // ...
    friend POINT operator+ ( const POINT& point, const POINT& point2 );
    // ...
};

POINT operator+ ( const POINT& point, const POINT& point2 )
{
    POINT temp;
    temp.x = point.x + point2.x;
    temp.y = point.y + point2.y;
    
    return temp;
}

//...
// ...

int main ()
{
    POINT a, b,  c;
    a.read( 'A' ); // say 2 3
    b.read( 'B' ); // say 5 7

    c = a + b; // will contain 7 10
}


EDIT

now, it's up to you how you will display the members of c
Last edited on
A less friendly approach has:
1
2
3
4
5
6
T operator+ ( const T & lhs, const T & rhs )
{
  T temp{ lhs };
  temp += rhs; // requires T& T::operator+= ( const T& )
  return temp;
}
Topic archived. No new replies allowed.