我是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'模板......听起来并不像你甚至还尝试过任何东西......? –