0

Loan &removeFirst () {} というメソッドを実行するたびに、プログラムがクラッシュし続けます。作成した一時的なローン構造を削除しようとすると、プログラムがクラッシュします。コンテナー クラスの背景と関数のコードを示します。

class ListOfLoans {

public:

    //default constructor allocate appropriate heap storage 
    //store elements on heap array declared like this: 
    //new Loan*[initial_size];
    ListOfLoans(int initial_size = 4) {
        elements = new Loan*[initial_size];
        numberOfElements = 0;
        capacity = initial_size;
        index = 0;
    }

    ~ListOfLoans(void) {
        cout << "Deleting \n";
        delete [] elements;
    }


    // answer the first element from the list but don't remove it
    Loan & first() const {
        if (capacity == 0) {
            cout << "Attempted on empty list. Exitting!" << endl;
            exit;
        } else {
            return *elements[0];
        }
    }

    // answer the first element from the list and remove it from the list
    // if the resulting list is more than three quarters empty release some memory
Loan & removeFirst() {
    index--;

    if (capacity == 0) {
           cout << "Attempted on empty list. Exitting!" << endl;
           exit;
    }

    if(size() < capacity/4) {  //shrink the container when 1/4 full 
      cout << "shrinking\n"; 
      Loan **temp = elements; 
      elements = new Loan*[capacity/2]; 
      for(index = (numberOfElements - 1); index >= 0; index--) {elements[index] = temp[index];}
      capacity /= 2; 
      delete [] temp; // my program crashes at this line, I want to delete the temp structure
    } 
      return first();
    }


private: 

    Loan ** elements; 
    int     numberOfElements; //number of elements in the list 
    int     capacity; //size of the available array memory 
    mutable int index; //used to help with the iteration

};
4

2 に答える 2