如何在main函数中接受整数输入,并在任何类中创建该大小的数组
how to take an integer input in main function and make an array of that size in any class?
例如
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);
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 在C++中为链表类创建实例
- 如何限制在C++中为单个类创建的对象数量?
- 如何使用模板化类创建其他类的实例?
- C++ 为 costum 类创建一个 const 迭代器
- C++为具有引用成员变量的类创建复制构造函数
- 在C++中,友元类可以从友元类创建对象吗
- 为静态类创建指向对象的指针是否合法?
- 如何从一组派生类创建列表?
- 如何使用 void 函数从类创建数组
- 如何从继承的父类创建unique_ptr
- 为什么我们不能用抽象类创建容器?
- 为 2D 向量类创建标量乘法运算符
- 一般函数中类的概括为基类创建对象代码
- 我正在考虑为"A"类创建复制构造函数,但我不确定采用哪种方法
- 从抽象类创建链
- 如何为抽象基类创建模板实例化?
- 在任何类类型上使用模板方法中的 new
- 在c++中,当我们创建一个类而不扩展到任何类时
- 如何在main函数中接受整数输入,并在任何类中创建该大小的数组