我想在运行时创建具有用户定义大小的类的对象。 就像当用户输入 5 时,它会创建 5 个对象。 这个我试过了
student s[num];
for(int i=0;i<num;i++)
{
student s[i]; // also used student s[i]=new student();
}
但是它说 student s[num]
expression must have constant value。
那么如何做到这一点呢?
最佳答案
A std::vector
就是为了这个目的而制作的。 (基本上是一个动态分配的数组)它有一个构造函数,用于预分配和构造元素的数量:
#include <vector>
std::vector<student> students(num);
您可以将其作为普通数组进行循环:
for(unsigned int i = 0; i < students.size(); ++i)
{
//students[i]..
}
或者,如果您可以访问 C++11,请使用基于范围的循环:
for(auto const& student : students)
{
//student..
}
或者,它是迭代器:
for(std::vector<student>::iterator itr = students.begin(); itr != students.end(); ++itr)
{
//access with *itr..
}
关于c++ - 在 C++ 中创建一类用户定义大小的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40307106/