我一直在尝试创建一个函数来乘以2个4x4矩阵,而不必复制其中一个。 我确实将矩阵定义为一个主要排序的简单数组列。
我来到的结果显示在下面的功能中。 出于某种原因,每次我尝试这样的事情:
matrix4 position = matrix4::identity();
position *= matrix4::identity();
我得到的翻译成英文应该是这样的:
在MFU-Core.exe中的0x010004B6处生成异常:0xC0000005:尝试在0x00E50000上写入时发生访问冲突。
此行的例外点。
elements[x + y * 4] = sum;
我在这里遗漏了什么吗? 提前谢谢!
完成.cpp文件:
namespace mfu { namespace maths {
//Default constructor
//Creates a 4x4 matrix filled with zeroes
matrix4::matrix4()
{
for (int i = 0; i < 4 * 4; i++)
elements[i] = 0.0f;
}
matrix4::matrix4(float diagonal)
{
//Fills every element with 0
for (int i = 0; i < 4 * 4; i++)
elements[i] = 0.0f;
//Replaces diagonal elements with diagonal
elements[0 + 0 * 4] = diagonal;
elements[1 + 1 * 4] = diagonal;
elements[2 + 2 * 4] = diagonal;
elements[3 + 3 * 4] = diagonal;
}
//Matrix format = mat[row + column x 4]
matrix4& matrix4::multiply(const matrix4& other)
{
//All the rows
for (int y = 0; y < 4; y++)
{
//All the columns
for (int x = 0; y < 4; x++)
{
float sum = 0.0f;
//All the elements
for (int e = 0; e < 4; e++)
{
sum += elements[x + e * 4] * other.elements[e + y * 4];
}
elements[x + y * 4] = sum;
}
}
return *this;
}
matrix4 operator*(matrix4 left, const matrix4& right)
{
return left.multiply(right);
}
matrix4& matrix4::operator*=(const matrix4& other)
{
return multiply(other);
}
}}
完整的头文件:
namespace mfu { namespace maths {
struct matrix4
{
float elements[4 * 4];
matrix4();
matrix4(float diagonal);
static matrix4 identity();
matrix4& multiply(const matrix4& other);
friend matrix4 operator*(matrix4 left, const matrix4& right);
matrix4& operator*=(const matrix4& other);
};
答案 0 :(得分:-1)
在您的所有列中,您的循环永远不会完成。您应该测试x
而不是y
//All the columns
for (int x = 0; x < 4; x++)