在运行时 c++ 更改用类对象填充的数组的大小

Change size of array filled with class objects at runtime c++

本文关键字:填充 数组 对象 c++ 运行时      更新时间:2023-10-16

>我有一个类,它必须存储动物的重量和它的类型。 根据用户的需求,可以在运行时创建该类的任意数量的实例。 我的问题是无法正确声明一个动态数组,一旦整个数组被对象填充,该数组就可以调整自身大小。

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/