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

标签 c++ arrays class

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

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/

相关文章:

c++ - 如何在 if 语句后运行多个函数

c++ - 在 C++ 中使用 setjmp() 和 longjmp() 有安全的方法吗?

c++ - 在另一个类内存分配中创建一个类

jquery - 与 jQuery 选择器一起使用的 CSS 类命名的最佳实践

c++ - VC++ 中的光纤安全优化到底是什么?

javascript - 在 nav ul li h4 中使用 jQuery 添加/删除链接类

c++ - 无法检测到 USB 设备

c++ - 使用唯一的指针调用函数会使我的程序崩溃

c# - 类数组初始化类C#

javascript - 仅打印单击的单选按钮值(React)