2015-05-09 66 views
-2

我是C++的新手,並且有關於異常處理和給我的問題的模板的任務。我不明白爲什麼我的捕獲不起作用。之前‘)’標記預期不合格-ID有人能解決這個問題,並解釋爲什麼我得到這個錯誤C++異常處理和模板

感謝所有誰可以指導我

編輯:我得到「錯誤。?:根據Tony D的評論,catch和compiler可以工作,但是不會打印catch消息。異常類錯誤不能正常工作,因爲我編碼。有關如何修復該類的任何提示?

這是我的程序:

// This program demonstrates an overloaded [] operator. 
#include <iostream> 
#include <cstdlib> 
using namespace std; 

class IntArray 
{ 
    private: 
    int *aptr; 
    int arraySize; 

public: 
    IntArray(int);  // Constructor 
    IntArray(const IntArray &); // Copy constructor 
    ~IntArray();   // Destructor 
    int size() const { return arraySize; } 
    void subError() const; // Handles subscripts out of range 
    int &operator[](int) const; // Overloaded [] operator 
}; 
class Error 
{ 
public: 
int value; 
Error(int i) 
{ 
    value=i; 
} 
}; 
IntArray::IntArray(int s) 
{ 
    arraySize = s; 
    aptr = new int [s]; 
    for (int count = 0; count < arraySize; count++) 
     *(aptr + count) = 0; 
} 
IntArray::IntArray(const IntArray &obj) 
{ 
    arraySize = obj.arraySize; 
    aptr = new int [arraySize]; 
    for(int count = 0; count < arraySize; count++) 
     *(aptr + count) = *(obj.aptr + count); 
} 
IntArray::~IntArray() 
{ 
    if (arraySize > 0) 
    { 
     delete [] aptr; 
     arraySize = 0; 
     aptr = NULL; 
    } 
} 
void IntArray::subError() const 
{ 
    cout << "ERROR: Subscript out of range.\n"; 
    exit(0); 
} 
int &IntArray::operator[](int sub) const 
{ 
    if (sub < 0 || sub >= arraySize) 
     throw Error(*aptr); 
    return aptr[sub]; 
} 
int main() 
{ 
const int SIZE = 10; // Array size 

// Define an IntArray with 10 elements. 
IntArray table(SIZE); 
try 
{ 
// Store values in the array. 
    for (int x = 0; x < SIZE; x++) 
    { 
      table[x] = (x * 2); 
    } 
// Display the values in the array. 
    for (int x = 0; x < SIZE; x++) 
    { 
     cout << table[x] << " "; 

    } 
    cout << endl; 
    // Try to print an element out of bounds 
    cout << table[-1] << endl; 
} 
catch(const Error&) 
{ 
    table.subError(); 
} 
return 0; 
} 
+0

好,你至少試着寫了' catch'語句,但對於'min'模板......聽起來並不像你甚至還嘗試過任何東西......? –

回答

1

I can't figure out why my catch isn't working.

Error類沒有嵌套您IntArray類中,所以更改...

catch(const IntArray::Error) 

...到...

catch(const Error&) 
+0

這有效,但是我應該在錯誤函數中更改什麼,以便該投擲是否有效? – TheJons

+0

@TheJons拋出應該已經「工作」的一些定義的「工作」 - 它應該編譯並達到catch塊,但1)你可能想'拋出錯誤(子):'所以它記錄無效索引和捕捉的代碼可以顯示它(你現在正在把'aptr'追蹤的數組中的第一個數字 - 這似乎是任意的和不相關的),2)一旦你發現異常,你不想'cout <

+1

非常感謝您的提示Tony D.我一直想念我想要嘗試代碼並在catch塊中留下表[-1]很長時間的事實。 – TheJons