gpt4 book ai didi

c++ - 在类中存储对象列表

转载 作者:搜寻专家 更新时间:2023-10-31 01:38:38 25 4
gpt4 key购买 nike

C++ 的新手,试图弄清楚如何创建一个我可以在其中存储对象列表的类。

我有一个包含三角形、圆形等子类的表面类。我正在尝试创建一个名为 Scene 的类,我可以用它来存储所有表面的列表。

这是我要执行的操作的头文件。你如何在 C++ 中做到这一点?

class Scene

{
private:
//background color elements
float bgRed;
float bgGreen;
float bgBlue;
//array of different surfaces
Surface surfaces[]; //<--- What I want


public:
Scene();
addSurface(Surface s);
};

最佳答案

有很多可能性,这里有一个简单的std::vector:

vector<Surface> surfaces;
...
addSurface(const Surface &s) //const and & are not strictly necessary, but better
{
surfaces.push_back(s);
}
...
//accessing like an array: surfaces[index]
//element count: surfaces.size()

这会在插入时复制传递的对象 (s)。如果您想要同一个对象,那么 vector 中的变化也会影响“外部”对象(反之亦然),您将需要一个额外的指针。
另请注意,复制 Surface 的子类对象将得到一个纯 Surface,没有子类部分(对象切片)。如果你需要那部分,你也需要一个指针(如果你还没有)。

//pointer variant
vector<Surface*> surfaces;
...
addSurface(Surface &s)
{
surfaces.push_back(&s);
}

关于c++ - 在类中存储对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32576242/

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