C++动态阵列索引和容量问题



我的家庭作业是要求我构建一个动态数组和其他函数。我已经设法完成了其余的问题,但有一个我不明白的错误......

目前,如果我设置D[0]=11D[1]=12,无论数组有多大,数组中的所有值都将变为 12,随之而来的容量将变为 12。

这些是我认为在下面相关的代码,我将根据请求提供更多代码。

输出

template <class dynElem>
class dynarr {
  private:
    int capacity;
    dynElem *A;
  public:
    dynarr() : capacity(0), A(NULL){};
    dynarr(int N): capacity(N), A(new dynElem[N]){}
    dynarr(const dynarr<dynElem> &other);
    ~dynarr();
    dynarr<dynElem> & operator=( const dynarr<dynElem> &other);
    dynElem & operator[](int ndx) throw(InvalidIndex);
    int getCapacity();
    void reserve(int newcap);
};
template <class dynElem>
dynarr<dynElem>::dynarr(const dynarr<dynElem> &other)
{
    capacity = other.capacity;
    A = new dynElem[capacity];
    for (int i = 0; i < other.capacity; i++) {
        A[i] = other.A[i];
    }
}
template <class dynElem>
dynarr<dynElem>::~dynarr()
{
    delete[] A;
}

测试.cpp

int main()
{
  dynarr<int> D(15);
  std::cout << "The capacity of D is " << D.getCapacity() << std::endl;
  D[0] = 11;
  D[1] = 12;
  std::cout << "D[0] = " << D[0] << std::endl; //12
  std::cout << "D[1] = " << D[1] << std::endl; //12
  std::cout << "The capacity of D is " << D.getCapacity() << std::endl; //12
  return 0;
}

@someprogrammerdude要求的额外代码:

template <class dynElem>
dynElem & dynarr<dynElem>::operator[](int ndx) throw(InvalidIndex)
{
    if (ndx < 0) {
        throw InvalidIndex("Array Index is negative");
    }
    else if (ndx > capacity) {
        throw InvalidIndex("Array Index is too large");
    }
}
template <class dynElem>
int dynarr<dynElem>::getCapacity()
{
  return capacity;
}
我很

惊讶你的代码居然在没有警告的情况下编译(我的编译器会对我大喊大叫)。您"忘记"从 operator[] 返回值。这是你应该做的。

template <class dynElem>
dynElem & dynarr<dynElem>::operator[](int ndx) throw(InvalidIndex)
{
    if (ndx < 0) {
        throw InvalidIndex("Array Index is negative");
    }
    else if (ndx > capacity) {
        throw InvalidIndex("Array Index is too large");
    }
    return A[ndx];   // here we return the element.
}

顺便说一句,在现代C++中,您的编码方式略有不同(除了您永远不会重新实现std::vector):

template<typename T>
class dynarr {
    std::size_t _capacity =0;    // set default values for initialisation
    std::unique_ptr<T[]> ptr;    // don't worry about de-allocation
  public:
    dynarr() = default;          // no need to define a destructor either
    dynarr(std::size_t N)
      : _capacity(N), ptr(new T[N]) {}
    dynarr(const dynarr&);
    dynarr& operator=(const dynarr&);
    T& operator[](size_t i);                // no need for throw()
    T const& operator[](size_t i) const;    // version for const access
    size_t capacity() const noexcept
      { return _capacity; }
    void reserve(size_t new_capacity);
};

相关内容

  • 没有找到相关文章

最新更新