0

我为 Stack 编写了一个函数,其中函数 top() 显示了堆栈的顶部:

class RuntimeException{
    private:
    string errorMsg;
    public:
    RuntimeException(const string& err){errorMsg = err;}
    string getMessage() const {return errorMsg;}
    };

class StackEmpty : public RuntimeException{
public:
StackEmpty(const string& err) : RuntimeException(err){}
};

template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    try{
        if(empty()) throw StackEmpty("Top of Empty Stack");
        return S[t];
        }
    catch(StackEmpty& se){
        cout << se.getMessage()<<"\n";
        }
    }


int main()
{
    ArrayStack <int> A;

    cout << "######\n";
    cout << A.top() << "\n";
        cout << "######\n";

    }

它显示以下编译警告:

$ g++ -Wall Stack.cpp -o Stack
Stack.cpp: In member function `const E& ArrayStack<E>::top() const [with E = int]':
Stack.cpp:91:   instantiated from here
Stack.cpp:61: warning: control reaches end of non-void function

输出是:

$ ./Stack
######
Top of Empty Stack
6649957
######

有人能说出警告的内容以及如何解决吗?另外输出中的数字“6649957”表示什么?

谢谢

4

1 回答 1

1

StackEmpty抛出的情况下,函数不返回任何内容,尽管它应该返回const E&

template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    try{
        if(empty()) throw StackEmpty("Top of Empty Stack");
        return S[t];
        }
    catch(StackEmpty& se)
    {
        cout << se.getMessage()<<"\n";
        // Return operator is missing ! Possibly you want this:
        throw;
   }
}

编辑。 这是使用方法抛出的异常的方法。您需要在客户端代码中捕获异常,而不是在方法本身中。

template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    if(empty()) throw StackEmpty("Top of Empty Stack");
    return S[t];
}

int main()
{
    ArrayStack <int> A;

    try
    {
        cout << "######\n";
        cout << A.top() << "\n";
        cout << "######\n";
    }
    catch(StackEmpty& se)
    {
        cout << se.getMessage()<<"\n";
    }
}
于 2013-04-10T05:39:05.507 回答