【发布时间】:2019-09-06 09:02:05
【问题描述】:
我有一个类必须存储动物的重量和类型。 根据用户的需要,可以在运行时创建尽可能多的该类的实例。 我的问题是无法正确声明一个动态数组,一旦整个数组都被对象填充,它就可以自行调整大小。
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。 -
C++ 没有variable-length arrays。请改用
std::vector。