函数删除太多

Function removes too much

本文关键字:太多 删除 函数      更新时间:2023-10-16

我正在做一个电话注册表,在其中你需要能够添加、删除和显示库存的手机。我已经可以添加手机,但是每当我添加3部手机并删除第二部手机时,第三部和第二部手机都会被删除,我不明白为什么。

这是我的CellPhoneHandler.h文件:

#ifndef CELLPHONEHANDLER_H
#define CELLPHONEHANDLER_H
#include "CellPhone.h"
class CellPhoneHandler
{
private:
    CellPhone **phone;
    int nrOfPhones;
    int priceOfPhone;
    int stockCapacity;
    int nrOfPhonesInArr;
public:
    CellPhoneHandler();
    ~CellPhoneHandler();
    void addPhone(string brand, int nrOf, int price);
    bool removePhoneFromStock(string name, int nrOf);
    int getNrOfPhones() const;
    int getNrOfPhonesInArr() const;
    int getPrice() const;
    void getPhonesAsString(string arr[], int nrOf, int priceOfPhone) const;
};
#endif // !CELLPHONEHANDLER_H

这是我的手机处理程序.cpp文件。

#include "CellPhoneHandler.h"
CellPhoneHandler::CellPhoneHandler()
{
    this->phone = nullptr;
    this->nrOfPhones = 0;
    this->priceOfPhone = 0;
    this->stockCapacity = 0;
    this->nrOfPhonesInArr = 0;
}
CellPhoneHandler::~CellPhoneHandler()
{ 
    for (int i = 0; i < nrOfPhonesInArr; i++)
    {
        delete phone[i];
    }
    delete[] phone;
}
void CellPhoneHandler::addPhone(string brand, int nrOf, int price)
{
    if (stockCapacity < nrOfPhonesInArr + 1)
    {
        CellPhone ** tempArray = new CellPhone*[this->nrOfPhonesInArr + 1];
        for (int i = 0; i < nrOfPhonesInArr; i++)
        {
            tempArray[i] = this->phone[i];
        }
        delete[] this->phone;
        this->phone = tempArray;
        this->phone[this->nrOfPhonesInArr] = new CellPhone(brand, nrOf, price);
        this->nrOfPhonesInArr++;
        //this->stockCapacity++;
    }
}
bool CellPhoneHandler::removePhoneFromStock(string name, int nrOf)
{
    bool phoneFound = false;
    int index = nrOfPhonesInArr;
    for (int i = 0; i < nrOfPhonesInArr; i++)
    {
        if (this->phone[i]->getBrand() == name);
        {
            index = i;
            phoneFound = true;
            this->nrOfPhonesInArr--;            
        }
    }
    if (phoneFound == true)
    {
        delete phone[index];
        phone[index] = nullptr;
    }
    return phoneFound;
}
int CellPhoneHandler::getNrOfPhones() const
{
    return this->nrOfPhones;
}
int CellPhoneHandler::getNrOfPhonesInArr() const
{
    return this->nrOfPhonesInArr;
}
int CellPhoneHandler::getPrice() const
{
    return this->priceOfPhone;
}
void CellPhoneHandler::getPhonesAsString(string arr[], int nrOf, int priceOfPhone) const
{
    for (int i = 0; i < nrOf; i++)
    {
        arr[i] = this->phone[i]->toString();
    }
}

问题是由不需要的;引起的。

    if (this->phone[i]->getBrand() == name);  // if ends here.

对所有项目执行下一个块。

    {
        index = i;
        phoneFound = true;
        this->nrOfPhonesInArr--;            
    }

删除if行中的该;