返回一个int数组在C

返回一个int数组在C

本文介绍了返回一个int数组在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在C ++的一个4x4矩阵类,我存储每个值作为浮动:

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;
}

我的问题是,我怎么可以把这些信息返回的float数组?我没有问题,建立在类数组例如:

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.

推荐答案

如果您的内部数组看起来像 int数组这会工作[4] [4]

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();

不过,这两种情况下暴露你的类的内部工作到外面的世界,有使你的code更不安全和难以维护。

But both cases expose the internal workings of your class to the outside world, with makes your code less safe and harder to maintain.

这将是最好创建一个拷贝构造函数,一个()运营商,并赋值运算符为​​你Matrix4d类,只是通过周围。你会不太可能有运行时错误是由于坏的内存管理或数据损坏。

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;

或本检索:

float attributeCopy = aMatrix(0,0);

这两种方式都可以。

It works both ways.

编辑:忘了 [] 运营商只用了一个参数。改变了运营商的()运营商a.k.a功能运营商。

Forgot that the [] operator only took one argument. Changed the operator to the () operator a.k.a the functional operator.

这篇关于返回一个int数组在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:37