开发者

Clearing a vector<pointer> and then reusing it

Ok, so I have a class called Company() that stores a vector<pointer>; (private)

Then I have a base class called StaffMember() that has two dervived classes (Manager and Casual) that are stored in the vector

I want to be able to clear the vector when editing the list or deleting from it but when I use function such as Company::StaffMembers.clear(); it crashes and throws a

"Unhandled exception at 0x00e182f4 in Payroll System.exe: 0xC0000005: Access violation reading location 0x00000005."

exception at me!

What am I doing wrong!


Company.h

#include "StaffMember.h"
#include "Manager.h"
#include "Casual.h"
#include <vector>
using namespace std;

class Company
{
private:
    vector<StaffMember*> StaffMembers;
public:
    Company();
    void addEmployee( StaffMember* pp );

    void editEmployee( int id, string fname, string lname, double salary );
    void editEmployee( int id, string fname, string lname, int hours, double rate );

    void deleteEmployee( int id );
    StaffMember* getStaffMember( int id );
    int StaffMemberCount();
};

Company.cpp

void Company::deleteEmployee( int id )
{
    // Impossible
    // Can not delete from vector

    // index will be the id of the employee
    int index = (-1);
    int size = Company::StaffMembers.size();

    for(int i=0;i<size;i++)
    {
        // If the current member's id is the same as the one we are looking for
        if(Company::StaffMembers[i]->getID()==i开发者_如何学运维d)
        {
            index=i;
            break;
        }
    }

    // Index is the id of the Employee we wish to delete
    Company::StaffMembers.erase(Company::StaffMembers.begin() + index );
}


Maybe you need to make sure a correct id has been found. Check that index != -1 before you perform the erase.


My guess is your program is crashing on this line:

       if(Company::StaffMembers[i]->getID()==id)

because one of the elements in your vector is null. But that's just a guess.

You should really run your code in a debugger, once you know the line of code you're crashing on it gets much easier to spot the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜