【发布时间】:2011-11-23 06:35:32
【问题描述】:
我在编写以下代码时遇到了一些麻烦。我不能写一个抛出异常,所以我不知道我还能做什么。
case 't': // Top of Stack
try
{
cout << "Top() -- " << sPtr->Top() << endl; //this should run if the stack is not empty.
}
catch (StackEmpty)
{
cout << "Top() -- Failed Empty Stack" << endl; // this should run if the stack is empty.
}
break;
sPtr 指向类名堆栈中的 Top() 函数,这里是该函数的代码:
int Stack::Top() const // Returns value of top integer on stack WITHOUT modifying the stack
{ cout << "*Top Start" << endl;
if(!IsEmpty())
return topPtr->data;
cout << "*Top End" << endl;
}
如果我删除 if 语句会导致分段错误问题。
【问题讨论】:
-
在学习编写 C++ 代码时,检查每个
if而不检查else并确保真的这是你想要的。
标签: c++ exception-handling segmentation-fault try-catch stack