Problem with passing class to a function

Hey guys!
I'm new to C++ and I'm trying to solve a simple problem - calculate the distance between two points in a plane with known coordinates.

Here is the source.

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
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

typedef class
{
private:
	int x;
	int y;
public:
	void get_coords(int a, int b) 
	{
		x = a;
		y = b;
	};
	int get_x() 
	{
		return x;
	}
	int get_y()
	{
		return y;
	}
}X;

float distance(X Point1, X Point2);
int sqr(int n);

int main ()
{
    X A, H;

	A.get_coords(0, 0);
	H.get_coords(0, 4);
	
	cout << distance(A, H);

        return 0;	
}

float distance(X Point1, X Point2) 
{
	return sqrt(sqr(abs(Point1.get_x() - Point2.get_x())) + sqr(abs(Point1.get_y() - Point2.get_y())));
}

int sqr(int n) 
{
    return n*n;
}


The problem is that I can't pass the 2 points to the distance(...) function. Any help will be appreciated.

You shouldn't use the form:
1
2
3
typedef class
{
} X;

It comes from C, but isn't correct in C++. You should use:
1
2
3
class X
{
};


sqrt seems to be overloaded for long double, double and float, not for int. So you need to convert your int coordinates to one of these floating point types.
Same thing. Dev C++ returns these errors :

In instantiation of `std::iterator_traits<X>':
instantiated from here
no type named `iterator_category' in `class X'
no type named `value_type' in `class X'
no type named `difference_type' in `class X'
no type named `pointer' in `class X'
no type named `reference' in `class X'
It might be helpful if you called your class Point rather than X.

Anyway, you need to make a change like:
1
2
3
4
5
6
7
float distance(X Point1, X Point2) 
{
	float dx = Point1.get_x() - Point2.get_x();
	float dy = Point1.get_y() - Point2.get_y();

	return sqrt(dx*dx + dy*dy);
}


Oh, distance is an STL function. There's a clash because you've used:
 
using namespace std;


Call it something else.
Last edited on
The compiler returns the same errors. Is there a possibility that the compiler is the problem ?

Edit: Renamed the distance() function. It works now :). Thanks alot!
Last edited on
Topic archived. No new replies allowed.