作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个类必须存储动物的重量及其类型。根据用户的需要,可以在运行时创建尽可能多的该类实例。我的问题是无法正确声明一个动态数组,一旦整个数组都充满了对象,它就可以自行调整大小。
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/
我是一名优秀的程序员,十分优秀!