Lor*_*ano 2 c++ stack templates
我见过与此类似的问题,但由于找不到使用模板的问题,因此没有一个对我有帮助。对于家庭作业,我必须编写一个可用于任何类型变量的堆栈,因此我决定使用模板。这阻止了我初始化变量,我的代码给了我一个关于 pop() 函数的警告,谁能给我关于如何删除这样的警告的建议?
我的函数 pop():
template<typename T>
T stack<T>::pop(){
T result;
if(!empty()){
result = tos->data;
Node<T> *tmp = tos;
tos = tos->next;
delete tmp;
}else{
std::cerr<<"ERROR empty stack"<<std::endl;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果它遇到它无法处理的东西,而不是简单地打印到std::cerr你的pop()方法应该抛出异常。静默失败并返回未初始化的对象将在以后导致问题。
你可以抛出这样的异常:
//...
else {
throw std::runtime_error("ERROR empty stack");
}
//...
Run Code Online (Sandbox Code Playgroud)
然后您只需要result在trueif 语句的分支中声明。