My home work is to ask me to build a dynamic array and with other functions. I've managed to complete the rest of the problems but there is one bug I don't understand...
Currently if I set D[0]=11
and D[1]=12
, no matter how big the array is, all values in the array will turned into 12, along with the capacity with it will become 12.
These are the codes I think is relevant below, I will provide more per request.
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;
}
test.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;
}
Aucun commentaire:
Enregistrer un commentaire