我已经使用链表为堆栈实现了一个简单的模板化类:
template <typename T>
struct Element
{
T data;
Element<T> *next;
};
template <typename T>
class Stack
{
private:
Element<T> *m_top;
public:
Stack(); // create an empty stack
void push(T value);
T pop();
T top();
bool isEmpty();
};
在 top()
的实现中,它返回存储在堆栈顶部元素中的值而不删除它,我收到以下错误:
警告:控制到达非 void 函数的末尾 [-Wreturn-type]
我已启用 -std=c++11 -pedantic -Wall
选项与 g++
。这是 top()
:
template <typename T>
T Stack<T>::top()
{
if (this->isEmpty()) // isEmpty() returns true if m_top == nullptr, false otherwise
{
std::cerr << "Stack empty!" << std::endl;
}
else
{
return m_top->data;
}
}
因为只有两个可能的值 - 堆栈为空或不为空,因此 if-else
构造。但是,我应该在 std::cerr
语句之后的 if
子句中放置什么才能使编译器满意并且不会收到警告?我不能简单地放置一个 return;
语句,因为编译器期望返回一个值。此外,如果堆栈为空,则不会返回任何内容。
其他帮助:
当您知道程序的逻辑是正确的时,让编译器提示是一个好习惯吗?
最佳答案
在像你这样的情况下,如果返回任何东西在逻辑上是不正确的,你应该抛出一个异常让程序停止:
if (this->isEmpty()) {
std::cerr << "Stack empty!" << std::endl;
throw std::logic_error( "calling top when stack is empty is illegal" );
} else {
return m_top->data;
}
关于c++ - "warning: control reaches end of non-void function [-Wreturn-type]"是否有合理的修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37412629/