每当我尝试在堆栈为空时将数字加在一起时,我试图在我的堆栈程序中抛出一个错误。在我的堆栈类的顶级函数中,我抛出一个异常,以防堆栈上没有任何东西。然后我继续在我的主程序中创建一个 try and catch block 来捕获错误并显示一条消息。但是,我收到下面列出的错误,但我不知道如何修复它。
错误:
terminate called after throwing an instance of 'char const*'
顶级类():
const T& top() const throw (std::string){
if(m_next != NULL){
return m_data;
}
else{
throw("Nothing on the Stack");
}
};
int main():
int main(){
string op;
RobotCalc<int>* stack = new RobotCalc<int>;
int operand1;
int operand2;
cin >> op;
while(op != "@"){
if(op == "+"){
try{
operand1 = stack->top();
stack->pop();
operand2 = stack->top();
stack->pop();
stack->push(operand1 + operand2);
}
catch (string e){
cout << e;
}
}
代码还有很多,但这就是问题所在。类函数有 2 个成员变量:T 类型的 m_data(在本例中为 int)和指向下一个 RobotClass(堆栈成员)的指针。这是堆栈的链表版本。
最佳答案
您正在捕获 string
类型的消息,而 throw 正在抛出 const char*
。捕获 const char*
或者只是放一个 ".
关于C++ try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19697069/