问题描述
我目前在C ++中有一个4x4矩阵类,并将每个值存储为一个float:
Matrix4d :: Matrix4d const float& m00,const float& m01,const float& m02,const float& m03,
const float& m10,const float& m11,const float& m12,const float& m13,
const float& ; m20,const float& m21,const float& m22,const float& m23,
const float& m30,const float& m31,const float& m32,const float& m33)
{
_m00 = m00;
_m01 = m01;
_m02 = m02;
_m03 = m03;
_m10 = m10;
_m11 = m11;
_m12 = m12;
_m13 = m13;
_m20 = m20;
_m21 = m21;
_m22 = m22;
_m23 = m23;
_m30 = m30;
_m31 = m31;
_m32 = m32;
_m33 = m33;
}
我的问题是,如何返回这个数据的float数组?我在类中创建数组没有问题,例如:
float arrayToReturn [16] = {m00,m01,m02, m03,... m33};
但是我不能从类返回这个值。我已经阅读过关于返回指向数组的指针,但没有运气。
内部数组看起来像 float array [4] [4]
:
float ** Matrix4d :: getMatrix();
如果您的内部数组是一维数组:
float * Matrix4d :: getMatrix();
但是这两种情况都会将类的内部工作暴露给外部世界,
最好创建一个复制构造函数,一个()
运算符,您的Matrix4d类的赋值运算符,只是传递它。
您的()
您可能会遇到由于内存管理错误或数据损坏而导致的运行时错误。运算符将如下所示:
float&
{
//返回正确的属性
}
您可以像这样设置值:
aMatrix )= 2.0;
或用于检索:
float attributeCopy = aMatrix(0,0);
这两种方式都有效。
:忘记了
[]
操作符只接受一个参数。将操作符更改为()
运算符a.k.a函数运算符。I currently have a 4x4 matrix class in C++ and I store each value as a float:
Matrix4d::Matrix4d(const float& m00, const float& m01, const float& m02, const float& m03, const float& m10, const float& m11, const float& m12, const float& m13, const float& m20, const float& m21, const float& m22, const float& m23, const float& m30, const float& m31, const float& m32, const float& m33) { _m00 = m00; _m01 = m01; _m02 = m02; _m03 = m03; _m10 = m10; _m11 = m11; _m12 = m12; _m13 = m13; _m20 = m20; _m21 = m21; _m22 = m22; _m23 = m23; _m30 = m30; _m31 = m31; _m32 = m32; _m33 = m33; }
My question is, how can I return a float array of this data? I have no problem creating the array in the class for example:
float arrayToReturn[16] = { m00, m01, m02, m03, ... m33 };
However I can not return this value from the class. I've read about returning a pointer to the array, but have had no luck with it.
解决方案This would work if your internal array looked like
float array[4][4]
:float** Matrix4d::getMatrix();
If your internal array was a one-dimensional array:
float* Matrix4d::getMatrix();
But both cases expose the internal workings of your class to the outside world, with makes your code less safe and harder to maintain.
It would be better to create a copy constructor, a
()
operator, and an assignment operator for your Matrix4d class and just pass that around. You'd be less likely to have runtime errors due to bad memory management or data corruption.Your
()
operator would look like this:float& operator()( unsigned int xIndex, unsigned int yIndex ) { //return the right attribute }
You would call it like this for setting values:
aMatrix(0,0) = 2.0;
or this for retrieving:
float attributeCopy = aMatrix(0,0);
It works both ways.
EDIT: Forgot that the
[]
operator only took one argument. Changed the operator to the()
operator a.k.a the functional operator.这篇关于在C ++中返回一个float数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!