gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:51:07 24 4
gpt4 key购买 nike

我有一个类必须存储动物的重量及其类型。根据用户的需要,可以在运行时创建尽可能多的该类实例。我的问题是无法正确声明一个动态数组,一旦整个数组都充满了对象,它就可以自行调整大小。

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。可以找到 vector 类的文档 here .

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);
}

关于c++ - 在运行时更改用类对象填充的数组的大小 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818898/

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