如何对类对象使用delete函数

How to use delete function for a class object?

本文关键字:delete 函数 对象      更新时间:2023-10-16

这个程序是一个学生数据库,具有添加和删除学生和课程的功能。我有一个问题,成功地从数据库中删除一个特定的学生。此外,当我尝试使用新的学生ID向数据库添加多个学生时,它会指出该学生已经在数据库中,而不应该在数据库中。我已经为学生附加了对象类和添加和删除函数的代码片段。任何帮助都将非常感激。欢呼。

class student {
public:
    int studentid;
    course * head;
    student (int id){ studentid = id; head = nullptr;}
    student () {head = nullptr;}
};
void add_student(student DB[], int &num_students)
{ 
    int ID;
    cout << "Please enter the id of the student you wish to enter " << endl;
    cin >> ID;
    for(int x = 0; x <num_students; x++)
    { 
        if (DB[x].studentid == ID);
    {  
    cout << "the student is already in the Database" << endl; return; } }
    student numberone(ID);
    DB[num_students] = numberone;
    num_students++; 
}
void remove_student(student DB[], int &num_students)
{ 
    int ID;
    cout << "Enter the student id you wish to delete from the Database " << endl;
    cin >> ID;
    // This is where I have the error
    // student * pointer2 = student(ID);
    //   delete pointer2; 
}

不能使用'delete'操作符,除非使用'new'操作符创建对象

student * pointer2 = student(ID); //wrong 
delete pointer2; 

第一个选项是

 student pointer2(ID) //no need to use delete operator here

在此选项中'。'操作符用于访问类成员。示例

pointer2.studentId

第二选项

delete操作符用于释放使用new操作符分配的内存

student * pointer2 = new student(ID);
delete pointer2; 

这里的'->'操作符用于访问类成员。示例

pointer2->studentId