如果数组索引超出范围,则尝试抛出范围错误(C++)
std::range_error如果我的函数访问的数组索引越界,我试图让我的程序抛出一个。传入的类型是size_t,因为堆栈中的内存位置可能是有符号的,也可能是无符号的。
这是我尝试过的:
MyClass::MyClass(){ // default constr
size = 10;
ptr = new int[size];
}
int MyClass::at(size_t position) const
{
try
{
return ptr[pos];
}
catch (const std::range_error&)
{
cout << "Range Error" << endl;
}
}
int main() {
// Test exceptions
MyClass a;
throw_(a.at(0), range_error);
}
任何人都可以帮助更正我的函数,以便range_error在索引超出范围时抛出 a吗?
回答
您的班级应该始终知道数组的大小。您可以立即知道传递的值是否超出范围并抛出。
你try不能工作。operator[]()不扔。它用作简单的内存偏移。
您的函数应该更像这样:
int MyClass::at(size_t position) const
{
if (position >= this->m_size) throw std::out_of_range("Bad idx passed to at()");
return ptr[position];
}