【问题标题】:Change size of array filled with class objects at runtime c++在运行时更改用类对象填充的数组的大小 c++
【发布时间】: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++ arrays class


【解决方案1】:

数组不能在 C++ 中改变大小。您需要使用动态容器,例如std::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);
}

【讨论】:

    【解决方案2】:

    使用标准库中的std::vectorpush_back() 方法添加新元素

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

    【讨论】:

      【解决方案3】:

      正如一些程序员老兄和 Ron 在 cmets 中提到的,C++ 默认不支持可变长度数组。如果您需要,std::vector 类是一个有用的工具。

      关于向量的一些基本信息: http://www.cplusplus.com/reference/vector/vector/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-20
        • 2012-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-02
        • 2019-01-16
        相关资源
        最近更新 更多