gpt4 book ai didi

c++ - 从类返回数组

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:51 25 4
gpt4 key购买 nike

我需要返回 3 个值。 X、Y、Z。我已经尝试过类似的方法,但它不起作用,任何人都可以帮助我吗?我看过这里:Return a float array in 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
}
};

最佳答案

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

类似于:

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

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

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

关于c++ - 从类返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3788391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com