gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:16:35 24 4
gpt4 key购买 nike

这是数组的类模板。我重载了 [ ] 运算符,希望它能解决“越界”问题。打印输出效果很好,除非超出范围,编译器默认启用范围并显示 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?
}

现在:

I overloaded the [ ] operator in hopes it would fix the "out of bounds" issue.

你没有修复任何东西。您只允许阵列的客户定义自定义边界,仅此而已。考虑:

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

您的代码是否检查像这样的越界情况?没有。

你应该这样做:

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 文档:

It is a standard exception that can be thrown by programs. Some components of the standard library, such as vector, deque, string and bitset also throw exceptions of this type to signal arguments out of range.

关于C++代码改进,数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29907359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com