尝试将元素添加到动态数组

Trying to add an element to a dynamic array

我尝试将 class 类型的元素添加到空动态数组,但没有任何反应,添加一个元素后也没有更改计数器。 这是函数

void Bank::addCustomer(const Customer& newCustomer) {

    Customer* temp = new Customer[getCustomerCount()+1]; 

    for (int i = 0; i < getCustomerCount() + 1 ; ++i) {
        if (getCustomerCount() != 0) {
            temp[i] = customers[i];
        }
    }

    ++customerCount;
    setCustomerCount(customerCount);
    delete[] customers; 
    customers = temp;

    customers[customerCount] = newCustomer; 
    //log
}

如果旧数组不为空,则您的循环超出了旧数组的边界。你对 newCustomer 的赋值超出了新数组的范围。

试试这个:

void Bank::addCustomer(const Customer& newCustomer) {

    int count = getCustomerCount(); 
    Customer* temp = new Customer[count + 1];

    for (int i = 0; i < count; ++i) {
        temp[i] = customers[i];
    }
    temp[count] = newCustomer; 

    delete[] customers; 
    customers = temp;

    ++customerCount;

    //log
}

我猜这就是你的意思:

void addCustomer(const Customer& newCustomer) {
    int old_customer_count = getCustomerCount();
    int new_customer_count = old_customer_count + 1;

    Customer* temp = new Customer[new_customer_count];
    for (int i = 0; i < new_customer_count; ++i) {
        temp[i] = customers[i];
    }

    setCustomerCount(new_customer_count);
    delete[] customers;
    customers = temp;
    customers[old_customer_count] = newCustomer;
}

但正如有人所说,在实际代码中,您应该 std::vector 用于客户集合。

尝试对动态数组使用 vector。 arry 不能是动态的。 push_back() 函数可用于向向量添加元素。