我已经使用链表这样为堆栈实现了一个简单的模板化类:
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()
返回存储在堆栈顶部元素中的值而不删除它的实现中,出现以下错误:
warning: control reaches end of non-void function [-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
构造。但是,在if
语句之后的子句中放置什么,std::cerr
以使编译器满意并没有得到警告?我不能简单地发表一条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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句