简体   繁体   English

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

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

I have a class that has to store the weight of the animal and it's type. 我有一个课程,必须存储动物的重量和它的类型。 Depending on what the user wants, there can be as many instances of that class created at runtime. 根据用户的需要,可以在运行时创建该类的多个实例。 My problem is with not being able to properly declare a dynamic array that can resize itself once the entire array has been filled with objects. 我的问题是无法正确声明一个动态数组,可以在整个数组填充对象后调整自身大小。

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)


and the end of the program 和程序的结束


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

Use the std::vector from the standard library and the method push_back() to add new elements 使用标准库中的std::vectorpush_back()方法添加新元素

http://www.cplusplus.com/reference/vector/vector/ http://www.cplusplus.com/reference/vector/vector/

Array cannot change size in C++. 数组不能在C ++中改变大小。 You need to use a dynamic container such as std::vector . 您需要使用动态容器,例如std::vector A documentation of the vector class can be found 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);
}

As mentioned in the comments by Some programmer dude and Ron, variable-length arrays are not supported in C++ by default. 正如一些程序员dude和Ron的评论中所提到的,默认情况下C ++不支持可变长度数组。 The std::vector class is a useful tool should you require them. 如果需要,std :: vector类是一个有用的工具。

Some basic info about vectors: http://www.cplusplus.com/reference/vector/vector/ 有关矢量的一些基本信息: http//www.cplusplus.com/reference/vector/vector/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM