尝试将元素添加到动态数组
我尝试将一个从类类型添加到一个空的动态数组中,但是什么也不会发生,也没有在添加一个元素后更改计数器。 这是功能
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
}
i've tried to add an element from class type to an empty dynamic array, but nothing happens, nor it changes the counter after adding one element.
This is the function
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的循环不为空,则超过旧数组的边界。
newcustomer
的分配超出了新数组的界限。而是尝试一下:
Your loop is exceeding the bounds of the old array if it is not empty. And your assignment of the
newCustomer
is exceeding the bounds of the new array.Try this instead:
我猜这就是您的意思:
但是正如某人所说,在实际代码中,您应该为客户收集
std :: vector
。I'm guessing this is what you mean:
but as someone said, in real code you should an
std::vector
for the customers collection.尝试使用向量进行动态阵列。阿里不能动态。 push_back()函数可用于将元素添加到向量。
Try using vector for dynamic array. arry cann't be dynamic. push_back() function can be used for adding element to vector.