[英]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.