mardi 29 septembre 2020

Classes and code throwing errors and strange unexpected behavior

I am working on a tiny project. And I am running into some issues, I've been trying to figure this out for weeks now. But, I finally decided to come to SO, and post this here. I am trying to get two of my functions to work properly:

Remove(...) and SearchWithName(...), I am using the C++ Range-based for loops. But, the Remove doesn't delete the pointer of Employee in Array. I get some memory thrown error. And for some reason, even if names match, or don't match I still get matched. Strange. I am trying to make it partially match or full match.

class Employee {
    
public:
    Employee() = default;
    Employee(std::string name, std::string address);
    
    std::string getName() { return this->name; }
    std::string getAddress() { return this->address; }
    
private:
    std::string name = "";
    std::string address = "";
    
};

class EmployeeArray {
public:
    EmployeeArray(int max) : max(max) {
        employees = new Employee[max];
    }
    
    void remove(Employee* e) {
        for(Employee* ee=employees; ee!=employees + current_total; ++ee)
        {
            if(ee == e){
                delete ee;
                ee = nullptr;
                current_total--;
            }
        }
    }
    
    Employee* SearchWithName(std::string name) {
        for(Employee* e = employee; e!=employees + current_total; ++e)
        {
            if(e->getName() == name)
            {
                return e;
            }
        }
        
        return NULL;
    } 
    
private:
    Employee* employees;
    int max = 0;
    int current_total = 0;
}

int main(){
    
    EmployeeArray* empArr = new EmployeeArray[2]
    {
        Employee("Richard Johnson", "1801 E 10th St Pueblo, CO 81001"),
        Employee("David Paras", "15 Spring St Rear Peabody, MA 01960"),
    }
    
    std::cout << (empArr->SearchWithName("lol") != NULL ? "Employee found!" : "This employee couldn't be found!") << std::endl;
    
    empArr->remove(*(Employee("Richard Johnson", "1801 E 10th St Pueblo, CO 81001"))));
    
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire