[英]C++ dynamic array of pointer to another class
您好,我正在尝试从Grades
类创建一个指向对象Student
的动态指针数组,但我不知道如何在标题中声明它
那是标题:
class Grades
{
private:
Student** array;
int _numofStud;
public:
Grades();
Grades(const Grades& other);
~Grades();
和成绩构造函数(我不确定它是对的)
Grades::Grades()
{
this->array = new Student * [2];
for (int i = 0; i < 2; ++i)
{
this->array[i] = NULL;
}
this->array[0]= new Student("auto1", "12345");
this->array[1]= new Student("auto2", "67890");
this->_numofStud = 2;
}
该probleme是之前就进入到构造函数,它创造了我5号的阵列中的Grades
,因为我在学生构造5种元素
Student::Student(const char* name, char* id)
{
this->_numofgrade = 0;
this->setName(name);
this->setId(id);
this->_grades = NULL;
this->_average = 0;
}
我不能添加或修改这个尺寸
我想将一个默认大小的 Grades 放在一个包含 2 个指向学生对象的指针的数组中,我将其定义为默认值,然后我将有其他方法通过创建新学生并将他们的指针添加到数组中来添加新学生 问题是我无法改变数组的大小,我不明白为什么
我希望我的解释很清楚,谢谢你的帮助
那是调试器,你可以看到当它创建一个新对象 Grades g1 它正在创建一个 5 的数组而不是两个按照我的要求先填充 2,剩下的 3 我不知道它们为什么被创建以及它们里面是什么
好的,要明确一点,在任何实际程序中,您都应该使用std::vector
或其他容器,它们有很多我在这里忽略的功能(模板、支持移动语义、不需要默认构造函数等),一个很多安全性(如果构造函数抛出异常怎么办?如果我执行array.add(array[0])
怎么办?),同时仍然针对通用用途进行了很好的优化。
而且您还应该真正查看std::unique_ptr
,手动new
, delete
,通常要求泄漏和其他错误,在 C++ 中几乎从不需要手动“释放”或“删除”任何资源。
另请注意,在 C++ 中size_t
通常用于对象和容器的大小/长度。
所以动态数组的基本思想是它根据当前的要求改变它的大小,例如Grades()
可以从空开始。
Grades::Grades()
: array(nullptr), _numofStud(0)
{}
然后当添加一个新项目时,会创建一个新的更大的数组,并复制所有现有项目(大致是std::vector::push_back(x)
所做的)。
void Grades::addStudent(Student *student)
{
// make a larger array
Student **newArray = new Student*[_numofStud + 1];
// copy all the values
for (int i = 0; i < _numofStud; ++i)
newArray[i] = array[i]; // copy existing item
// new item
newArray[_numofStud] = student;
++_numofStud;
// get rid of old array
delete[] array;
// use new array
array = newArray;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.