如何在main函数中接受整数输入,并在任何类中创建该大小的数组

how to take an integer input in main function and make an array of that size in any class?

本文关键字:任何类 创建 数组 输入 函数 main 整数      更新时间:2023-10-16

例如

class Quota{
    private:
        int t_quota, intake, ID[];
        float percentage[];
};

这是我要修改的类。下面是主要函数,我将从中传递一个整数值来设置Quota类中两个数组的大小。

int main(){
    int intake;
    cout<<"Enter the total number of students who took the test this session of 2015, September: ";
    cin>>intake;
    Quota qr(intake);
}

我在这里要做的是使两个数组的大小,即ID[]percentage[]的"摄入量"。比如,ID[intake], percentage[intake]。这能做到吗?我想是这样,但我试过通过构造函数,但没有得到正确的。有人知道怎么做吗?

不能创建在编译时未知的固定大小的数组。这意味着需要在构造函数中分配所需大小的数组,然后在析构函数中释放它。

但是我建议使用std::vector

class Quota{
    Quota(const int size): ID(size), percentage(size)
    {
    }
    private:
        int t_quota, intake;
        std::vector<int> ID;
        std::vector<float> percentage;
};

实际上,我们应该避免在c++中使用底层数据结构,比如array。您应该使用vector<int> ID, vector<float> percentage,而不是ID[], percentage[]。然后可以在Qouta的构造函数中设置ID and percentage的大小。例如:

Quota::Quota(const int& intake)
{
    ID.resize(5); //set ID's size
    percentage.resize(5);
}

我希望这对你有帮助

当您在运行时确定数组的大小时,您不能在编译时初始化它。

也许你可以尝试先分配它,然后分配一个指针。这是可行的。但是我不确定它是否符合你的要求。

class Quota{
public :
    Quota(int size);
    int *  allocate_ID(int size);
private:
    int t_quota, intake;
    int * ID;
    float percentage[];
 };
 Quota::Quota(int size)
 {
     ID = allocate_ID(size);
 }
 int * Quota::allocate_ID(int size)
 {
     int * ID_arr = new int[size];
     return ID_arr;
 }
int main(){
     int intake;
     cout<<"Enter the total number of students who took the test this session of 2015, September: ";
     cin>>intake;
     Quota qr(intake);
 }