C++类中的动态数组

Dynamic array in class C++

本文关键字:动态 数组 C++      更新时间:2023-10-16

我有一个类的成员是dynamic array(我在pastebin中发布了我的代码),我想知道我的两个类是否都是正确的,它们是否有什么问题?此外,我需要如何编写(41行)一个将类Student设置为StudentsDynamicArray的函数?

这是我的阵列类

class StudentsDynamicArray{
private:
Student *Stud;// students dynamic array
int n; // current size of array
int nmax; // max size of array
public:
StudentsDynamicArray():n(0), Stud(NULL), nmax(0){}
StudentsDynamicArray(int n):
n(n){}
~StudentsDynamicArray(); // destructor
void SetStud(Student S){Stud[n++] = S;} // I get error when I try to set String or Int.    //How I need to change this?
Student GetStud(int i){return Stud[i];}
void IncreaseSize(int ns);
};
//Function which change size of array
void Student::ChangeSize(int kiek){
if(kiek > nmax){
int *SNEW = new int[kiek];
for(int i=0; i<n; i++)
SNEW[i] = mark[i];
delete [] mark;
mark = SNEW;
nmax = kiek;
}
else if(kiek < nmax){
int *SNEW = new int[kiek];
for(int i=0; i<n; i++)
SNEW[i] = mark[i];
delete [] mark;
mark = SNEW;
n = nmax = kiek;
}
}

在学生课堂上,你有

int *mark

这表明必须应用三条规则:复制构造函数、赋值运算符和析构函数。前两个应该复制动态数组,析构函数应该释放内存。您只正确地实现了析构函数。这同样适用于StudentsDynamicArray类。

对于:

void SetStud(Student S){Stud[n++] = S;} 

从您的代码来看,您最初似乎没有调用IncreaseSize,一旦调用SetStud,Stud可能为NULL。你可以通过在构造函数中调用它来修复它:

StudentsDynamicArray():n(0), Stud(NULL), nmax(0){ IncreaseSize(10); }

此外,如果您使用std::vector,则上述所有内容都是不必要的,因此,如果您不需要这样的低杠杆动态阵列,则使用std::vector。然后你们会使用零规则。

[编辑]

您的复制构造函数/赋值运算符应该如下所示:

Student (const Student& other) {
// here allocate this->mark to be the same size as in other
// copy values from other.mark to this->mark
// also copy other values from `other` to this
}
Student& operator= (const Student& other)
{
// here allocate this->mark to be the same size as in other
// copy values from other.mark to this->mark
// also copy other values from `other` to this
return *this;
}

正如你所看到的,它们"非常"相似。关于"三条规则"的Wiki实际上更新到了C++11,在那里您可以添加移动语义,从而提高按值复制操作的效率(实际上被称为"五条规则")。如果你正在学习基础知识,你可以坚持以前的规则。

您可以更好地使用std::vector将学生打包到集合中。这将显著提高性能,并减少错误。

下面是您可以使用的类的原型。

class Student
{
private:
string mName;
unsigned int mAge;
public:
Student() : mName(""), mAge(0) {}
Student( string name, unsigned int age ) : mName(name), mAge(age) {}
string get_name() const;
void set_name( string name );
unsigned int get_age() const;
void set_age( unsigned int age ); 
};
class Students
{
private: 
vector<Student> mCollection;
public:
Students() : mCollection() { }
Students( vector<Student> &input_collection ) : mCollection( input_collection ) { }
Students &add_student( Student &s );
Students &remove_student( Student &s );
Students &remove_student( string name );
Students &remove_student( size_t index );
Students &edit_student( size_t index, string new_name, unsigned int new_age );
};

希望这能有所帮助。