I have two classes a 3D vector class(Vector3) with an array of 3 floats as its member(float[3]), and a 3 by 3 matrix class that stores 3 of these vectors in another array(Vector3[3]). My vector class requires the matrix class to rotate about an axis, and my matrix class requires vectors for everything. I was using forward declarations and pointers to deal with it, like in this question: What is the best way to deal with co-dependent classes in C++?, but there must be a better way to design this to avoid that altogether. At the moment I declare a pointer to Vector3 on my matrix header file, and then initialize it with new in my implementation file, yet this feels clumsy. Any pointers(no pun) on how to solve this issue? Edit: I use the vector class to represent a 3D point which I intend to rotate about an arbitrary axis.
The code as I would like it to work:
//Vector3.h
#include "Matrix3.h"
class Matrix3;
class Vector3 {
float xyz[3];
};
//Vector3.cpp
Vector3 Vector3::rotatePoint(Vector3 o, Vector3 a, float theta) {
Vector3 point = (*this);
Vector3 x = Vector3(1,0,0);
Vector3 y = Vector3(0,1,0);
Vector3 z = Vector3(0,0,1);
// Create new coordinate system
Vector3 new_coord[4];
new_coord[0] = o;
new_coord[1] = a.normalize();
unsigned closer_to;
if (a*x < a*y) {
new_coord[2] = (a % x).normalize();
closer_to = 0; // x
}
else {
new_coord[2] = (a % y).normalize();
closer_to = 1; // y
}
new_coord[3] = (a % new_coord[2]).normalize();
// Transform point to new coord system
Matrix3 trans_matrix = Matrix3(new_coord[0], new_coord[1], new_coord[2]);
point = trans_matrix*(point - o);
// Rotate about a by theta degrees
Matrix3 r_m(closer_to, theta);
point = r_m*point;
//Transform back to original coord system
point = (trans_matrix.inverse()*point) + o;
return point;
}
//Matrix3.h
#include "Vector3.h"
class Vector3;
class Matrix3 {
Vector3 rows[3];
}
The code that I use to make it work:
//Vector3.h
class Matrix3;
class Vector3 {
float xyz[3];
};
//Matrix3.h
#include "Vector3.h"
class Vector3;
class Matrix3 {
Vector3 *rows;
}
//Matrix3.cpp
Matrix3::Matrix3() {
rows = new V3[3];
}