我将如何创建可以拥有比0(C ++)等下界数组类? [英] How would I create an Array class that can have lower bounds other than zero (in C++)?

查看:119
本文介绍了我将如何创建可以拥有比0(C ++)等下界数组类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我迄今。当我试图访问一个索引越界它抛出一个异常。我试着说返回NULL如果范围是出界了重载下标操作符,但它不工作。问题是,当我尝试分配一个值超过上限允许它发生的指数。像目前的code,如果我改变< 8的主要功能< 9,它使用数组元素8而没有问题,但我希望它有一个问题。任何帮助是AP preciated。

This is what I have so far. It throws an exception when I try to access an index out of bounds. I tried to say "return NULL" if the range is out of bounds for the overloaded subscript operator, but it's not working. The problem is when I try to assign a value to an index above the upper limit it allows it to happen. Like with the current code if I change the "< 8" in the main function to "< 9", it uses array element 8 without problem, but I want it to have a problem with that. Any help is appreciated.

#include <iostream>
#include <stdexcept>
using namespace std;

//L for lower-bound, U for upper-bound
template <typename T, int L, int U>
class LBArray
{
    public:
      LBArray()
      {
        lbound = L;
        ubound = U;
        data = new T[ubound - lbound];
      }
      T& operator[](int index)
      {
        if (index < lbound || index > ubound)
        {
          throw out_of_range("index out of bounds");
        }
        return data[index - lbound];
      }
      ~LBArray()
      {
        if (data) delete[] data;
      }
    private:
      T *data;
      int lbound;
      int ubound;
};

int main(int argc, char** argv)
{
  LBArray<int, 5, 7> data;
  cout << "LBArray<int, 5, 7> data\n";
  for (int x = 5; x < 8; x++)
  {
    data[x] = x;
    cout << endl << "data[" << x << "] = " << data[x];
  }
  return 0;
}

推荐答案

您创建数组5-7,我想那5和7在内,那么你有3个元素的数据[5],数据[6],数据[7],但在你的code:

You create array from 5 to 7, and I suppose that 5 and 7 included, then you have 3 elements data[5], data[6], data[7], but in your code:

data = new T[ubound - lbound];

和这两个元素7-5 = 2。你失去了一个元素。
因此,我认为你需要做这样的:

and that 2 elements 7-5 = 2. You lose one element. Therefore I think you need do like that:

data = new T[ubound - lbound + 1];

这改变所有的工作很好,但你不使用在try..catch后,那么你的code关闭。
如果你不希望使用在try..catch,我提供给你下一个code:

After that change all work fine, but you do not use try..catch, then your code shutdown. If you do not want to use try..catch, I offer to you next code:

T& operator[](int index)
{
    if (index < lbound || index > ubound)
    {
        T nullVar = NULL;

        return (T&)nullVar;
    }
    return data[index - lbound];
}

试图获取元素与索引错误函数返回NULL。

Attempting to get element with wrong index the function return NULL.

这篇关于我将如何创建可以拥有比0(C ++)等下界数组类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆