在运行时 c++ 更改用类对象填充的数组的大小
Change size of array filled with class objects at runtime c++
>我有一个类,它必须存储动物的重量和它的类型。 根据用户的需求,可以在运行时创建该类的任意数量的实例。 我的问题是无法正确声明一个动态数组,一旦整个数组被对象填充,该数组就可以调整自身大小。
class FarmAnimal
{
private:
short int type;
int weight;
double WaterConsumed;
public:
static int NumberOfSheep;
static int NumberOfHorse;
static int NumberOfCow ;
static double TotalWaterUsed;
FarmAnimal(int type, int weight)
{
this->type = type;
this->weight = weight;
}
int CalculateWaterConsumption(void);
void ReturnFarmInfo(int& NumberOfSheep, int& NumberOfHorse, int& NumberOfCow, int& TotalWaterUsed)
};
int main()
{
...
short int k;
...
do
{
...
FarmAnimal animal[k](TypeOfAnimal, weight);
k++;
cout << "Would you like to add another animal to your farm?n Press"0" to exit and anything else to continue" << endl;
cin >> ExitButton;
} while (ExitButton != 0)
和程序的结束
animal[0].ReturnFarmInfo(NumberOfSheep, NumberOfHorse, NumberOfCow, TotalWaterUsed)
cout << " Your farm is made up of :" << NumberOfSheep << " sheeps " << NumberOfHorse" horses " << NumberOfCow << " cows " << endl;
cout << "The total water consumption on your farm per day is: " << TotalWaterUsed << endl;
}
数组不能更改C++的大小。您需要使用动态容器,例如std::vector
。可以在此处找到向量类的文档。
std::vector<FarmAnimal> animals;
bool done = false;
while (!done)
{
animals.push_back(FarmAnimal(TypeOfAnimal, weight));
cout << "Would you like to add another animal to your farm?n Press"0" to exit and anything else to continue" << endl;
cin >> ExitButton;
done = (ExitButton != 0);
}
使用标准库中的std::vector
和方法push_back()
添加新元素
http://www.cplusplus.com/reference/vector/vector/
正如一些程序员Dude和Ron的评论中提到的,默认情况下,C++不支持可变长度数组。如果需要的话,std::vector 类是一个有用的工具。
关于矢量的一些基本信息: http://www.cplusplus.com/reference/vector/vector/
相关文章:
- C++ 填充数组时遇到问题
- 如何使用同时设置计数和填充数组的函数
- 如何使填充数组的函数发送到函数?而不是其参数中的数组
- 如何使用文件填充数组并将其与用户输入C 进行比较
- 使用 memset 填充数组会显示垃圾
- Visual Studio从文件中填充数组时中断
- 分段 填充数组时出错
- 用不同的值填充数组/矢量的边缘和中心
- 使用相同的数据填充数组对象或使用指针
- 是否可以使用三元运算符"?"在 C/C++ 中填充数组列表?
- 填充数组(写入位置0x00000000的访问冲突)
- 从文件中读取输入并填充数组以存储数据供以后使用
- c++当循环在填充数组时没有正确终止时,希望能帮助退出此循环
- 填充数组会导致数组周围的堆栈损坏
- Cuda有效地将数据插入到未排序的填充数组中
- 填充数组的 C++ 函数
- 访问部分填充数组上的第一个打开元素
- 将一个字节数组从C#传递到C++填充数组的C++com对象中
- 如何使用向量中的信息填充数组并从数组中选择随机项
- C,填充数组使用dec2bin转换器