C++代码改进,数组越界

C++ code improvement, array out of bounds

本文关键字:数组 越界 代码 C++      更新时间:2023-10-16

这是一个数组的类模板。我重载了[ ]运算符,希望它能解决"越界"问题。打印输出效果良好,除非超出范围,编译器默认启用该范围,并显示一个6位数。

也许是在寻找一种更好的方法,用合适的元素编号初始化数组,以进行更好的检查,如果在查找元素时确实超出了范围,则显示错误。

// implement the class myArray that solves the array index 
// "out of bounds" problem.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
template <class T>
class myArray
{
private:
T* array;
int begin;
int end;
int size;
public:
myArray(int);
myArray(int, int);
~myArray() { };
void printResults();
// attempting to overload the [ ] operator to find correct elements.
int operator[] (int position)
{if (position < 0)
return array[position + abs(begin)];
else
return array[position - begin];
}
};

template <class T>
myArray<T>::myArray(int newSize)
{
size = newSize;
end = newSize-1;
begin = 0;
array = new T[size] {0};
}
template <class T>
myArray<T>::myArray(int newBegin, int newEnd)
{
begin = newBegin;
end = newEnd;
size = ((end - begin)+1);
array = new T[size] {0};
}
// used for checking purposes.
template <class T>
void myArray<T>::printResults()
{
cout << "Your Array is " << size << " elements long" << endl;
cout << "It begins at element " << begin << ", and ends at element " << end << endl;
cout << endl;
}
int main()
{
int begin;
int end;
myArray<int> list(5);
myArray<int> myList(2, 13);
myArray<int> yourList(-5, 9);
list.printResults();
myList.printResults();
yourList.printResults();
cout << list[0] << endl;
cout << myList[2] << endl;
cout << yourList[9] << endl;
return 0;
}

首先,您的operator[]不正确。它被定义为始终返回int。一旦实例化某个不能隐式转换为int的数组,就会出现编译时错误。

它应该是:

T& operator[] (int position)
{
//...
}

当然还有

const T& operator[] (int position) const
{
//you may want to also access arrays declared as const, don't you?
}

现在:

我重载了[]运算符,希望它能解决"越界"问题。

您没有修复任何内容。您只允许数组的客户端定义自定义边界,仅此而已。考虑:

myArray<int> yourList(-5, 9);
yourList[88] = 0;

您的代码是否检查像这样的out-of-bounds案例?编号

你应该这样做:

int operator[] (int position)
{
if((position < begin) || (position > end)) //invalid position
throw std::out_of_range("Invalid position!");
//Ok, now safely return desired element
}

请注意,在这种情况下,抛出异常通常是最好的解决方案。引用std::out_of_range文档:

这是一个标准的异常,可以由程序抛出。标准库的某些组件,如vectordequestringbitset,也会抛出此类型的异常,以发出超出范围的参数信号。

重新定义数组类的一个更好的选择是使用std库中的容器。矢量和数组(由c++11支持)。它们都有一个重载运算符[],因此您可以访问数据。但是,使用push_back(用于向量)方法添加元素并使用at方法访问元素可以消除出现超出范围错误的机会,因为at方法会执行检查,并在需要时调整push_back的向量大小。