C++ 返回数组并在另一个func中使用它
我使用以下函数用球体填充类“SolidSphere”的数组:C++ 返回数组并在另一个func中使用它,c++,arrays,pointers,return,return-value,C++,Arrays,Pointers,Return,Return Value,我使用以下函数用球体填充类“SolidSphere”的数组: SolidSphere *createSpheres() { SolidSphere *spheres[numSpheres]; for (int i = 0; i < numSpheres; i++) spheres[i] = new SolidSphere(1, 12, 24); return *spheres; } SolidSphere*createSpheres() { 实心
SolidSphere *createSpheres()
{
SolidSphere *spheres[numSpheres];
for (int i = 0; i < numSpheres; i++)
spheres[i] = new SolidSphere(1, 12, 24);
return *spheres;
}
SolidSphere*createSpheres()
{
实心球*球体[numSpheres];
对于(int i=0;i
现在我想在另一个函数中使用createSpheres的返回值:
void display()
{
for (int i = 0; i < numSpheres; i++)
spheres[i]->draw(posX,posY,posZ);
}
void display()
{
对于(int i=0;i绘制(posX,posY,posZ);
}
但是,inside display()“spheres”显示为未定义的标识符。我该如何进行?感谢您提供的帮助。您正在创建指针数组。尽管在堆上创建了
SolidSphere
对象,但数组本身仍在堆栈上,其作用域是函数createSpheres
的本地范围。因此,一旦函数执行完毕,它就会被销毁
您还需要在堆上创建数组:
SolidSphere **spheres = new SolidSphere*[numSpheres];
display
函数看不到spheres
数组的原因是spheres
是createSpheres
本地的;没有其他函数能够看到它
您的代码有几个问题:
- 您正在创建指向
的指针数组,但函数返回指向sphere的单个指针SolidSphere
- 如果您尝试按原样返回阵列,调用方将无法使用它,因为内存将丢失(它位于本地存储中)
SolidSphere
对象,最好的方法是返回其中的vector
。如果必须返回指针集合,则应使用智能指针(例如unique\u ptr
)而不是常规指针
如果您将此作为学习练习,并且必须为数组使用普通指针,则需要动态分配数组,如下所示:
SolidSphere **createSpheres()
{
SolidSphere **spheres = new SolidSphere*[numSpheres];
for (int i = 0; i < numSpheres; i++)
spheres[i] = new SolidSphere(1, 12, 24);
return spheres;
}
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()
是同一类的成员,则可以将spheres
作为该类的成员变量。然后,您可以在代码< >代码>显示> <代码> >代码> >代码> >代码> >代码> >空> <代码>,使用< <代码>显示> <代码>,因为它是成员变量。这是极端的基本C++。买本书。要么新建
数组本身并返回该指针,要么使用向量
,这就不那么麻烦了。麻烦少了:向量球(numSpheres,SolidSphere(1,12,24));对于(自动和s:球体)s.draw(posX、posY、posZ)代码>