简体   繁体   English

将对象数组存储在自己的 class c++

[英]Store array of objects in its own class c++

I'm new to c++ and i'm trying to make a simple game engine.我是 c++ 的新手,我正在尝试制作一个简单的游戏引擎。 I am trying to make a game object and component system.我正在尝试制作游戏 object 和组件系统。

I have a base class for all object and I am trying to store all children of the object in an array inside the class.我有一个所有 object 的基础 class 并且我正在尝试将 object 的所有子项存储在 ZA2F2ED4F8EBC2CBBDZC2A 内的数组中。 But i get an error when trying to make an array of the class inside the class.但是当我尝试在 class 中创建一个 class 数组时出现错误。

class Object {
    public: 
        Object children[]; //This is where I get the error
};

Is there a way to do this?有没有办法做到这一点? If not, how can I work around this issue?如果没有,我该如何解决这个问题?

Object children[] is a fixed size array. Object children[]是一个固定大小的数组。 For these types of arrays, the size needs to be known at compile time or else an error will be flagged by the IDE (the compiler might ignore it as the size of it is 0 but would flag a warning).对于这些类型的 arrays,需要在编译时知道大小,否则 IDE 将标记错误(编译器可能会忽略它,因为它的大小为 0,但会标记警告)。

You cannot do Object children[some_amount] as till be an incomplete type.你不能做Object children[some_amount]直到是一个不完整的类型。 So your option is to use a dynamically resizable array.因此,您的选择是使用可动态调整大小的数组。

For this, C++ standard library provides an excellent option in the name of std::vector .为此,C++ 标准库以std::vector的名义提供了一个极好的选项。 To use this you must include the vector header file.要使用它,您必须包含vector header 文件。 The way to use it is simple, for your case you can use it by this: std::vector<Object> children;使用它的方法很简单,对于您的情况,您可以通过以下方式使用它: std::vector<Object> children; and elements can be added at runtime using the std::vector<>::push_back() function.并且可以在运行时使用std::vector<>::push_back() function 添加元素。

Further information: https://en.cppreference.com/w/cpp/container/vector更多信息: https://en.cppreference.com/w/cpp/container/vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM