c++ - 在 C++ 中创建一类用户定义大小的对象

标签 c++

我想在运行时创建具有用户定义大小的类的对象。 就像当用户输入 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/

相关文章:

c++ - 不能在 Boost.Asio 中使用可移动物体

c++ - 在 C++ 中生成不同的随机数

c++ - 使用 ucnv_convert() 时为韩语显示垃圾字符

c++ - 如何在 C++ 中引用双重模板化的自由函数

c++ - 通过宏定义编译标志(C++11 和优化)

c++ - 代码重构后前向声明导致错误

c++ - 如何手写计算器的 C++ 语法?

C++ SDL 如何撤销 BlitSurface

c++ - Oracle Pro*C for insert with a sub select query causing ORA-01403 : no data found

c++ - std::cin 导致无限循环