c++ - "warning: control reaches end of non-void function [-Wreturn-type]"是否有合理的修复?

标签 c++ c++11

我已经使用链表为堆栈实现了一个简单的模板化类:

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/

相关文章:

c++ - 如何为成员函数创建一个可简单复制的委托(delegate)

C++ std::lower_bound() 函数查找索引排序 vector 的插入点

c++ - 为什么 std::make_tuple(7 + N...) 在 C++11 中是合法的?

c++ - STL 算法 copy if with functor

c++11 - CLion 无法解析线程

C++ - thread_local 变量存储在哪里?

c++ - 如何将谓词传递给算法

c++ - 如何覆盖 C++ 中的函数

c++ - SOIL图像加载库参数

C++ 让 Windows 服务启动另一个程序