C++ 数组根本不支持像 Pascal 那样的自定义边界。它们总是从索引 0 开始,以索引长度 1 结束。如果你想要类似 Pascal 的索引,你必须自己实现它,例如:
template<typename T, const int LowBound, const int HighBound>
class RangedArray
{
private:
T m_arr[HighBound-LowBound+1];
void CheckBounds(const int index)
{
if ((index < LowBound) || (index > HighBound))
throw std::out_of_range();
}
public:
int low() const { return LowBound; }
int high() const { return HighBound; }
T operator[](const int index) const
{
CheckBounds(index);
return m_arr[index-LowBound];
}
T& operator[](const int index)
{
CheckBounds(index);
return m_arr[index-LowBound];
}
};
.
RangedArray<char, 20, 40> arr;
arr[20] // OK
arr[15] // out of bounds
arr[60] // out of bounds
如果你想要更动态的东西,试试这个:
template<typename T, const int LowBound>
class RangedVector
{
private:
std::vector<T> m_vec;
void CheckBounds(const int index)
{
if ((index < low()) || (index > high()))
throw std::out_of_range();
}
public:
int low() const { return LowBound; }
int high() const { return m_vec.empty() ? -1 : (LowBound + m_vec.size() - 1); }
void setHighBound(const int HighBound)
{
if (HighBound < LowBound)
throw something;
m_vec.resize(HighBound-LowBound+1);
}
void push_back(const T &value)
{
m_vec.push_back(value);
}
T operator[](const int index) const
{
CheckBounds(index);
return m_vec[index-LowBound];
}
T& operator[](const int index)
{
CheckBounds(index);
return m_vec[index-LowBound];
}
};
.
RangedVector<char, 20> arr;
arr.setHighBound(40);
arr[20] // OK
arr[15] // out of bounds
arr[60] // out of bounds