简体   繁体   English

在C ++中的类中可以有可变数量的变量吗?

[英]Can you have a variable amount of variables in a class in C++?

This is my first question here, and I'm not very skilled at programming yet, so my apologies if I do something wrong. 这是我的第一个问题,我对编程还不太熟练,所以如果我做错了事,我深表歉意。 That said, I searched both here and on Google before asking the question, so if a duplicate exists, it's because I didn't know how to find it. 也就是说,在提出问题之前,我在这里和Google上都进行了搜索,因此,如果存在重复项,那是因为我不知道如何找到它。

My question is as per the title. 我的问题是按照标题。

I'm attempting to program a little procedural star system generator to refresh my memory and help grow my programming skills. 我正在尝试对一个程序性星形系统生成器进行编程,以刷新我的记忆并帮助提高我的编程技能。 I want to create a class for the solar system to hold data on the star(s) and planet(s), each of which will also be a class. 我想为太阳系创建一个类,以保存恒星和行星上的数据,每个恒星和行星上的数据也将是一个类。 So to illustrate my question for clarification: 因此,为了说明我的问题以进行澄清:

Is there a way to avoid having to declare, say, 10 different "planetClass" items in the class, and instead define one that scales as it's needed? 有没有一种方法可以避免必须在类中声明10个不同的“ planetClass”项,而是定义一个可以根据需要扩展的项? If not, is there an alternative, or do I just flat-out have to define up to the maximum variables needed? 如果没有,是否有其他选择,还是我必须完全定义所需的最大变量?

You can simply define a Planet class to store data for each planet, and then add a std::vector<Planet> data member into your "outer" class. 您可以简单地定义一个Planet类来存储每个行星的数据,然后将std::vector<Planet>数据成员添加到“外部”类中。

std::vector is a standard STL container class template, that can be dynamically (ie at run-time) resized. std::vector是标准的STL容器类模板,可以动态(即在运行时)调整大小。 You can add new items (in your case: Planet instances) to it, using its push_back() or emplace_back() methods. 您可以使用其push_back()emplace_back()方法向其中添加新项(在您的情况下为Planet实例)。

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

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