gpt4 book ai didi

c++ - 返回数组并在另一个函数中使用它

转载 作者:行者123 更新时间:2023-11-30 04:04:55 28 4
gpt4 key购买 nike

我使用以下函数用球体填充类“SolidSphere”的数组:

SolidSphere *createSpheres()
{
SolidSphere *spheres[numSpheres];
for (int i = 0; i < numSpheres; i++)
spheres[i] = new SolidSphere(1, 12, 24);

return *spheres;
}

现在我想在另一个函数中使用 createSpheres 的返回值:

void display()
{
for (int i = 0; i < numSpheres; i++)
spheres[i]->draw(posX,posY,posZ);
}

但是,在 display() 内部,'spheres' 显示为未定义的标识符。我该如何进行?感谢您提供的任何帮助。

最佳答案

display 的原因函数没有看到 spheres数组是 spheres是本地的 createSpheres ;其他功能将无法看到它。

您的代码有几个问题:

  • 您正在创建一个指向 SolidSphere 的指针数组,但您的函数返回一个单个指向球体的指针。
  • 如果您尝试按原样返回数组,调用者将无法使用它,因为内存会消失(它在本地存储中)。

如果你想返回一组SolidSphere对象,最好的方法是返回一个 vector他们中的。如果必须返回指针集合,则应使用智能指针(例如 unique_ptr<SolidSphere> )而不是常规指针。

如果您将此作为学习练习,并且您必须为数组使用普通指针,则需要动态分配数组,如下所示:

SolidSphere **createSpheres()
{
SolidSphere **spheres = new SolidSphere*[numSpheres];
for (int i = 0; i < numSpheres; i++)
spheres[i] = new SolidSphere(1, 12, 24);

return spheres;
}

现在您可以调用createSpheres()来自 display ,像这样:

void display()
{
SolidSphere **spheres = createSpheres();
for (int i = 0; i < numSpheres; i++) {
spheres[i]->draw(posX,posY,posZ);
}
// Now you need to free the individual spheres
for (int i = 0; i < numSpheres; i++) {
delete spheres[i];
}
// Finally, the array needs to be deleted as well
delete[] spheres;
}

如果createSpheres()display()是同一类(class)的成员,你可以制作spheres该类的成员变量。然后你可以制作createSpheres一个void函数,删除声明和返回,并使用 spheresdisplay , 因为它现在是一个成员变量。

关于c++ - 返回数组并在另一个函数中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23584964/

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