【发布时间】:2016-09-30 04:07:30
【问题描述】:
我有一个类 Matrix 和另一个类 Camera,我想在其中使用 Matrix。我的 Matrix 类如下所示:
class Matrix4f {
public:
Matrix4f() {
this->setMatrix(EMPTY);
}
Matrix4f(Matrix4f &m2) {
this->setMatrix(m2.matrix);
}
static Matrix4f& Matrix4f::identity() {
Matrix4f& identity = Matrix4f() ;
identity.setMatrix(IDENTITY);
return identity;
}
void setMatrix(float f[4][4]) {
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++) {
this->matrix[r][c] = f[r][c];
}
}
}
Matrix4f& operator=(const Matrix4f &m2) {
this->setMatrix(m2.matrix);
}
private:
float matrix[4][4];
static float EMPTY[4][4] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 }
}; // initialize an empty array (all zeros);
static float IDENTIY[4][4] = {
{ 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 }
}; // initialize a identity (array)
}
我的相机课上有这个:
class Camera {
public:
Camera() {
this->calculateProjection();
}
Matrix4f* getProjection() {
return this->projection;
}
private:
Matrix4f* projection;
Matrix4f* calculateProjection() {
this->projection = &Matrix4f::identity();
// modify this->projection...
return this->projection;
}
}
当我尝试创建一个 Camera 实例然后获取它的投影时,我得到的东西看起来像是一个损坏的对象(矩阵完全填充为大的负数)。
我真的很困惑是什么原因造成的我的代码会像这样行为不端。
我相当肯定它处理的是编译器自动删除的引用,我认为它处理的是单位矩阵,但它并没有真正的意义。
不应该将单位矩阵复制到投影矩阵中,这样单位矩阵是否被垃圾收集也没有关系?
我发现我实际上可以通过以下任一方式使这段代码工作
使单位矩阵创建一个新的 Matrix4f() 并返回该值或使 getProjection() 返回 calculateProjection()。
问题是,我真的不想做任何一个。
我不希望 Identity 构造一个新的 Matrix4f,因为我必须处理破坏它,而且我不想要 getProjection( ) 来调用 calculateProjection() 因为该方法很昂贵,
实际上应该只调用一次,因为投影矩阵永远不会改变。
【问题讨论】:
-
identity是什么? -
你为什么要在相机中使用指针?
-
你的班级名称是什么
Matrix或Matrix4f? -
关于身份:这是第一个错误的事情。没有参考。而且你需要一个更好的拷贝构造函数(const)。
-
摆脱指针(返回对象),摆脱重载的复制构造函数和赋值运算符,神奇地你会看到你的代码工作。
标签: c++ class pointers reference