[英]try-catch exception in c++
如果学生列表为空,我被要求使用try-catch异常处理来处理这种情况。 我是异常处理的新手,有人可以指导我吗? 下面是平均方法的实现。 我需要使用try-catch来确保列表不为空。
double classAverage()
{
int count = 0;
double sum = 0.0;
Container *temp = list;
if (temp == NULL)
{
cout << "List empty!";
return -1.0;
}
while (temp != NULL)
{
sum += temp->student->getGrade();
temp = temp->next;
count++;
}
return sum / count;
}
由于changeGrade
是Student
的朋友,因此应该可以:
void changeGrade(Student* s, int newGrade) {
s->grade = newGrade;
}
现在,您将指针s
指向新的Student
对象。 您想要的是更改传递给函数的对象。
没有足够的信息,但是我认为您的代码可能如下所示:
Student* student = new Student("John", "Doe", 99, 1);
changeGrade(student, 9);
这根本不会改变学生,因为您按值传递了指针,所以当您重新分配它时,原始对象(指针student
)不会改变。 为了使调用代码注意到更改,您必须通过引用传递( Student*&
-推荐方式)或使用指向指针的指针( Student**);
。 另外,如果您使用的是Student**
方法,请不要忘记删除原始指针( Student*
),否则会浪费内存。
int
,它可能是不好的做法,并且令人困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.