我是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;
}
好,你至少試着寫了' catch'語句,但對於'min'模板......聽起來並不像你甚至還嘗試過任何東西......? –