如何对 class 对象使用删除功能?
How to use delete function for a class object?
本程序是一个学生数据库,具有学生和课程的添加和删除功能。我在成功从数据库中删除特定学生时遇到问题。此外,当我尝试使用新的学生 ID 将多个学生添加到数据库中时,它指出该学生已经在数据库中,而他们不应该在数据库中。我附上了对象 class 的代码片段以及学生的添加和删除函数。任何帮助将不胜感激。干杯.
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
在此选项中,'.'运算符用于访问 class 成员。例子
pointer2.studentId
第二个选项
'delete'运算符用于释放使用'new'运算符
分配的内存
student * pointer2 = new student(ID);
delete pointer2;
此处'->'运算符用于访问class成员。例子
pointer2->studentId
本程序是一个学生数据库,具有学生和课程的添加和删除功能。我在成功从数据库中删除特定学生时遇到问题。此外,当我尝试使用新的学生 ID 将多个学生添加到数据库中时,它指出该学生已经在数据库中,而他们不应该在数据库中。我附上了对象 class 的代码片段以及学生的添加和删除函数。任何帮助将不胜感激。干杯.
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
在此选项中,'.'运算符用于访问 class 成员。例子
pointer2.studentId
第二个选项
'delete'运算符用于释放使用'new'运算符
分配的内存student * pointer2 = new student(ID);
delete pointer2;
此处'->'运算符用于访问class成员。例子
pointer2->studentId