Не работает оператор копирования назначений - PullRequest
0 голосов
/ 25 мая 2018

В моем коде возникли проблемы с оператором назначения копирования.Когда я пытаюсь выполнить оператор "=" в моем main(), содержимое моего исходного массива (numArr) не копируется в мой массив удалений (numArr2).

Затем, для моей функции doubleCap(), я пытаюсь создать больший массив двойного размера, как только мой исходный массив заполнится.Однако, если я вставлю delete[] newArr, компилятор выведет несколько случайных чисел в моем массиве.

Это мой код в .cpp

#include <iostream>
#include "NumList.h"

using namespace std;

//Default Constructor
NumList::NumList()
{
    //Actual elements stored in the array
    size = 0;
    //Max capacity of the array
    capacity = 1;
    numList = new int[capacity];
}

//Destructor
NumList::~NumList()
{
    delete[] numList;
}

//Copy Constructor
NumList::NumList(const NumList& anotherNumList)
{
    capacity = anotherNumList.capacity;
    size = anotherNumList.size;
    numList = new int[capacity];
    for (int i = 0; i < size; ++i)
    {
        numList[i] = anotherNumList.numList[i];
    }
}

//Copy Assignment Operator
NumList& NumList::operator= (const NumList& anotherNumList)
{
    //Check if it is self-assigning
    if (this == &anotherNumList)
        return *this;

    //Get rid of the old data
    delete[] numList;

    this->capacity = anotherNumList.capacity;

    //Create and copy to the new array
    numList = new int[capacity];

    for (int i = 0; i < anotherNumList.size; ++i)
    {
        numList[i] = anotherNumList.numList[i];
    }

    return *this;
}

void NumList::print()
{
    for (int i = 0; i < size; ++i)
    {
        cout << numList[i] << " ";
    }
    cout << endl;
}

void NumList::doubleCap()
{
    capacity = capacity * 2;
    //Create a new array when the capacity is full
    int * newArr = new int[capacity];

    for (int i = 0; i < size; ++i)
    {
        newArr[i] = numList[i];

    }
    //Let numlist points to the new array
    numList = newArr;

    //delete[] newArr; <-- 
}

void NumList::insertEnd(int val)
{
    //Double the capacity of the list
    if (size == capacity)
    {
        doubleCap();
    }
    numList[size] = val;
    ++size;
}

void NumList::insertAt(int val, int index)
{
    if (index < 0 || index > capacity)
    {
        cout << "The index is out of range." << endl;
    }
    else
    {
        //Double the capacity of the list
        if (size == capacity)
        {
            doubleCap();
        }
        for (int i = (size-1); i >= index; i--)
        {
            numList[i + 1] = numList[i];
        }
        numList[index] = val;
        ++size;
    }
}

Это мой код в main

#include <iostream>
#include <string>
#include <algorithm>
#include "NumList.h"

using namespace std;

int main()
{
    NumList numArr;
    NumList numArr2;

    numArr.insertEnd(10);
    cout << "List 1 after inserting 10: ";
    numArr.print();

    numArr2 = numArr;
    NumList numArr3(numArr);

    numArr.insertEnd(11);
    numArr.insertEnd(12);
    numArr.insertAt(5, 0);
    cout << "List 1: ";
    numArr.print();

    cout << "\nPrint the list 2 of int: ";
    numArr2.print();

    cout << "\nPrint the list 3 of int: ";
    numArr3.print();

    system("pause");
    return 0;

}

Вывод без строки "delete [] newArr;",

List 1 after inserting 10: 10 
List 1: 5 10 11 12

Print the list 2 of int: 

Print the list 2 of int: 10 
Press any key to continue . . . 

Вывод со строкой "delete [] newArr;",

List 1 after inserting 10: 10 
List 1: 5 -572662307 -572662307 12

Print the list 2 of int: 

Print the list 2 of int: 10 
Press any key to continue . . . 

1 Ответ

0 голосов
/ 25 мая 2018

Вы пытаетесь удалить не ту вещь.В doubleCap() у вас есть 2 массива, член и новый созданный вами, который имеет больше места.Тот, который имеет больше места, это тот, который вы хотите сохранить, поэтому вы не можете его удалить.Что вам нужно сделать, это удалить исходный массив, а затем назначить ему новый.Это делает функцию похожей на

void NumList::doubleCap()
{
    capacity = capacity * 2;
    //Create a new array when the capacity is full
    int * newArr = new int[capacity];

    for (int i = 0; i < size; ++i)
    {
        newArr[i] = numList[i];

    }

    delete [] numList; // get rid of the old array
    //Let numlist points to the new array
    numList = newArr;
}

Вам также не хватает назначения anotherNumList.size на this->size в вашем operator =.Это приводит к тому, что скопированный список имеет неправильный размер после назначения.

...