2011-09-22 127 views
0

我在使以下代碼工作時遇到了一些問題。我不能寫拋出異常,所以我不知道我還能做什麼。在類名嘗試拋出異常處理

case 't': // Top of Stack 
      try 
      { 
       cout << "Top() -- " << sPtr->Top() << endl; //this should run if the stack is not empty. 
      } 
      catch (StackEmpty) 
      { 
       cout << "Top() -- Failed Empty Stack" << endl; // this should run if the stack is empty. 
      } 
      break; 

的特徵碼點頂部()函數棧這裏是這個函數的代碼:

int Stack::Top() const // Returns value of top integer on stack WITHOUT modifying the stack 
{ cout << "*Top Start" << endl; 
if(!IsEmpty()) 
return topPtr->data; 
cout << "*Top End" << endl; 
} 

如果我刪除if語句,它會導致分段錯誤問題。

+0

當學習代碼C++,檢查每個'if'沒有'else'並_really_肯定這是你想要的。 –

回答

3

你沒有真正投擲造成任何影響,而在情況下,當堆棧是空的,你只是流失的結束函數不返回任何東西。另外你的最後的日誌語句只在堆棧爲空時才被命中。

你需要更多的東西是這樣的:

int Stack::Top() const // Returns value of top integer on stack WITHOUT modifying the stack 
{ 
    cout << "*Top Start" << endl; 
    if(!IsEmpty()) 
    { 
    cout << "*Top End" << endl; 
    return topPtr->data; 
    } 
    cout << "*Top End" << endl; 
    throw StackEmpty(); 
} 
+0

完美!我可以發誓我至少嘗試了兩次不同的時間,兩種不同的方式,這給了我一個錯誤,但無論如何再次感謝。 –

3

爲什麼「不能」拋出異常?請注意,如果您從Top()(當您的堆棧爲空時)沒有返回任何內容,則您要求發生問題。它應該是Top()的前提條件,即堆棧不是空的,所以如果你不能拋出異常,斷言是可以接受的,甚至比我更喜歡。

順便說一句,異常拋出這樣的:

throw StackEmpty(); 
+0

是的,謝謝。現在它工作。 –