Отрицательные числа при использовании оператора << для отображения содержимого массива - PullRequest
0 голосов
/ 17 октября 2019

Я получаю функцию увеличения емкости, если она полная. Но когда я вызываю оператора для отображения содержимого в массиве, я получаю все отрицательные числа. Я считаю, что мои указатели испорчены. Я студент, пытающийся учиться, поэтому, если вы можете понять это, объяснение может помочь.

template<class T>
class Container{
    template <class T>
    friend ostream& operator<<(ostream& out, Container<T> &cobj);
private:
    T *arry;
    int Capacity;
    int n;
public:
    Container();//the the container function, arry=NULL, Capaticty=0; and n=-1;
    ~Container();
    bool isEmpty();
    bool isFull();
    int Size();
    int capacity();
    void insertBack(T &NewVal);
    bool deleteBack();
    void clear();
    bool insertFront(T val);
    bool deleteFront();
    void allocate(T* &temp);
};

template <class T>  
void Container<T>::insertBack(T &NewVal){
    T *temp;
    temp = new T[Capacity];
    if (isFull())
    {
        allocate(arry);
        temp[NewVal];
        ++n;
        arry = temp;
    }
    else 
    {
        ++n;
        arry[n] = NewVal;
    }

}


// adding more space to the array if its full. This is where i think
// my pointers are all messed up.

template< class T>
void Container<T>::allocate(T* &temp){  
    temp = new T[Capacity];

    if (Capacity == 0)
        Capacity = (Capacity + 1);
    else
        Capacity = (Capacity * 2);
    temp[Capacity] = arry[Capacity];
} 

Это функция, которая будет отображать содержимое массива. тогда, когда я вызываю эту функцию, числа получаются отрицательными.

ostream& operator<<(ostream& out, Container<T> &cobj){
    cout << "Container storage capacity: " << cobj.Capacity << endl;
    cout << "Contents of the container: " << cobj.Size() << endl;
    if (cobj.isEmpty())
    {
        cout << "" << endl;
    }
    else
    {
        for (int i = 0; i <= cobj.n; i++)
        {
            cout <<" [" <<cobj.arry[i]<<"] " << endl;
        }
        cout << endl;
    }
    return out;
};


int main()
{
    Container<int> j;
    int level = 5;
    for (int i = 0; i < level; i++)
    {   
        int value=0;
        value = value + 10;
        j.insertBack(value);
    }

    cout << j << endl;

    system("pause");
}

Это то, что я получаю в качестве вывода

Container storage capacity: 8
Contents of the container: 5
 [-842150451]
 [-842150451]
 [-842150451]
 [-842150451]
 [-33686019]


Press any key to continue . . .
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...