When I save this as a .h-file:
Code:
#ifndef __Vector2D_SEEN__
#define __Vector2D_SEEN__
/////// Vector2D.h ///////
class Vector2D
{ public:
Vector2D() {}
Vector2D(float a, float b)
{ x=a; y=b; }
Vector2D difference(Vector2D& v);
float inner(Vector2D& a);
bool isParallel(Vector2D& v);
bool isPerpendicular(Vector2D& v);
bool nonzero()
{ return ( x != 0.0 || y != 0.0 ); }
void display();
/* other members not shown */
private:
float x, y;
};
#endif
And this as a .C-file (the functions to the class in the .h-file):
Code:
//////// Vector2D.C //////////
#include <iostream>
#include "Vector2D.h"
float Vector2D::inner(Vector2D& v)
{ return(x * v.x + y * v.y); }
void Vector2D::display()
{ std::cout << "(" << x << ", "
<< y << ")";
}
Vector2D Vector2D::difference(Vector2D& v)
{ Vector2D tmp;
tmp.x = x - v.x;
tmp.y = y - v.y;
return tmp;
}
inline float ABS(float x)
{ return (x > 0 ? x : -x); }
// test if the host is perpendicular to a
bool Vector2D::isPerpendicular(Vector2D& v)
{ return ( nonzero() && v.nonzero()
&& ABS(inner(v)) < 0.00000001 ); // delta = 0.00000001
}
// test if the host is parallel to a (pointing in the same direction)
bool Vector2D::isParallel(Vector2D& v)
{ return( nonzero() && v.nonzero() &&
x*v.x >= 0.0 &&
y*v.y >= 0.0 &&
ABS(x*v.y-y*v.x) < 0.00000001
);
}
And try to compile this:
Code:
#include <iostream>
#include <stdlib.h>
#include "Vector2D.h"
Vector2D getVec(int i) // input a point as vector
{ float x,y;
std::cout << "x" << i << "= ";
std::cin >> x;
std::cout << "y" << i << "= ";
std::cin >> y;
return Vector2D(x,y);
}
int main()
{
std::cout << "Enter vertices 0,1,2,3 "
<< std::endl;
Vector2D p[4];
for ( int i = 0; i < 4; i++) // input all four points
p[i] = getVec(i);
Vector2D u = p[0].difference(p[3]); // vector difference (2)
Vector2D v;
for (int i = 0; i < 3; i++) // process all sides
{ v = p[i+1].difference(p[i]); // vector difference (3)
if ( ! u.isPerpendicular(v) ) // check perpendicularity
{ std::cout << "No, not a rectangle." << std::endl;
return 1;
}
u = v;
}
std::cout << "Yes, a rectangle." << std::endl;
system("PAUSE");
return 0;
}
It doesn't work. If I move all the functions of the .C-file to the .h-file, so that it works under one in file, the program compiles successfully. Why is this?