C++代码改进,数组越界
C++ code improvement, array out of bounds
这是一个数组的类模板。我重载了[ ]
运算符,希望它能解决"越界"问题。打印输出效果良好,除非超出范围,编译器默认启用该范围,并显示一个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
文档:
这是一个标准的异常,可以由程序抛出。标准库的某些组件,如
vector
、deque
、string
和bitset
,也会抛出此类型的异常,以发出超出范围的参数信号。
重新定义数组类的一个更好的选择是使用std库中的容器。矢量和数组(由c++11支持)。它们都有一个重载运算符[],因此您可以访问数据。但是,使用push_back(用于向量)方法添加元素并使用at方法访问元素可以消除出现超出范围错误的机会,因为at方法会执行检查,并在需要时调整push_back的向量大小。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 缓冲区溢出 - 数组索引越界(严重)
- 分段错误:为什么这里的数组索引越界了
- 是什么导致了数组越界运行时错误?
- 数组越界或错误等于 nullptr?C++
- C++代码改进,数组越界
- C++:如何通过异常处理从越界数组返回值
- 为什么 Cppcheck 找不到这个明显的数组越界错误
- 如果我从未实际使用该引用,那么引用越界数组元素是否安全
- 为什么编译器允许越界数组访问,即使使用 constexpr 索引也是如此
- C++:写入/读取无效/越界数组索引
- 为什么 CppCheck 会为此静态 const 数组提供越界访问错误
- 埃拉托斯梯尼的筛子,数组太大,以至于内存越界
- 数组索引越界赋值的问题
- 为什么当我访问数组的越界元素时没有收到运行时错误?