从类返回数组

Sta*_*tan 1 c++

我需要返回 3 个值。X,Y,Z。我试过这样的事情,但它不起作用,有人能帮我一下吗?我在这里看过:在 C++ 中返回一个浮点数组,我尝试做同样的事情,除了要返回的一维数组。

class Calculate
{
 float myArray[3][4], originalArray[3][4], tempNumbers[4];
 float result[3]; // Only works when result is 2 dimensional array, but I need 1 dimension.

public:
 Calculate(float x1, float y1, float z1, float r1,
  float x2, float y2, float z2, float r2,
  float x3, float y3, float z3, float r3)
 {
  myArray[0][0] = x1;
  myArray[0][1] = y1;
  myArray[0][2] = z1;
  myArray[0][3] = r1;

  myArray[1][0] = x2;
  myArray[1][1] = y2;
  myArray[1][2] = z2;
  myArray[1][3] = r2;

  myArray[2][0] = x3;
  myArray[2][1] = y3;
  myArray[2][2] = z3;
  myArray[2][3] = r3;

  result[0] = 1;
  result[1] = 2;
  result[2] = 3;
 }

 float* operator[](int i)
 {
  return result[i]; //Value type does not match the function type
 }

 const float* operator[](int i) const
 {
  return result[i]; //Value type does not match the function type
 }
};
Run Code Online (Sandbox Code Playgroud)

Rei*_*ien 5

通常最好的做法是接受一个指针并在那里写出结果,而不是返回一个指针。这样,有人可以在堆栈上分配一个常规数组,并由您的计算对其进行初始化。

就像是:

class Calculate
{
 float myArray[3][4], originalArray[3][4], tempNumbers[4];

public:
 Calculate(float x1, float y1, float z1, float r1,
  float x2, float y2, float z2, float r2,
  float x3, float y3, float z3, float r3, float *result)
 {
  myArray[0][0] = x1;
  myArray[0][1] = y1;
  myArray[0][2] = z1;
  myArray[0][3] = r1;

  myArray[1][0] = x2;
  myArray[1][1] = y2;
  myArray[1][2] = z2;
  myArray[1][3] = r2;

  myArray[2][0] = x3;
  myArray[2][1] = y3;
  myArray[2][2] = z3;
  myArray[2][3] = r3;

  result[0] = 1;
  result[1] = 2;
  result[2] = 3;
 }
};
Run Code Online (Sandbox Code Playgroud)

您可以做一些其他调整 - 将构造函数与计算分开,因为构造函数更多用于初始化;并传递数组以进行更安全的内存控制:

class Calculate
{
    float myArray[3][4], originalArray[3][4], tempNumbers[4];

public:
    Calculate(const float initArray[3][4])
    {
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 4; j++)
                myArray[i][j] = initArray[i][j];
    }

    void DoCalculation(float result[3]) const
    {
        result[0] = 1;
        result[1] = 2;
        result[2] = 3;
    }
};

int main()
{
    float myArray[3][4] =
    {
        { 0, 1, 2, 3 },
        { 4, 5, 6, 7 },
        { 8, 9, 0, 1 }
    };
    float result[3];
    Calculate calc(myArray);
    calc.DoCalculation(result);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)