我試圖將一個元素從型別別添加到一個空的動態陣列,但沒有任何反應,也沒有在添加一個元素后改變計數器。這是功能
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
}
uj5u.com熱心網友回復:
如果它不為空,您的回圈將超出舊陣列的范圍。并且您的分配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
}
uj5u.com熱心網友回復:
我猜這就是你的意思:
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為客戶收藏。
uj5u.com熱心網友回復:
嘗試將向量用于動態陣列。arry 不能是動態的。 push_back()函式可用于將元素添加到向量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481230.html
