简体   繁体   中英

How can I use push_back() on a vector of pointers?

I have a Manager class. I made an addEmployee() method to add Employee objects to it by address:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

enum EmployeeLevel { A, B, C, D, E };
class Employee {
    string name;
    const EmployeeLevel level;
public:
    Employee(const string& _name, const EmployeeLevel _level)
        : name(_name), level(_level) {}
    Employee(const Employee& another)
        : name(another.name), level(another.level) {}

    friend ostream& operator << (ostream& os, const Employee& e);
};

ostream& operator << (ostream& os, const Employee& e) {
    os << e.level << e.name << endl;
}

class Manager : public Employee {
    vector<Employee*> group;
public:
    Manager(const string& _name, const EmployeeLevel _level)
        : Employee(_name, _level) {}

    void addEmployee(const Employee* e)
    {
        group.push_back(e);
    }
};

int main() {
    Employee e1("Hong", A), e2("Kim", B), e3("Cha", A);
    cout << e1 << e2 << e3;

    Manager m1("Tom", D);
    m1.addEmployee(&e1);
    m1.addEmployee(&e2);
    m1.addEmployee(&e3);
    cout << endl << "Information for Manager" << endl;
    cout << m1;
}

I thought since group is a vector , the push_back() method should work, but it's not working.

I cannot edit the main() function.

What is the problem??

Your addEmployee() was expecting a const Employee*. But your vector is storing an Employee* resulting in pushback failure. So change your addEmployee() as follows:

void addEmployee(Employee* e)
{
    group.push_back(e);
}

If you still want to keep the const pointer.You can modify the Addemployee function as follows:

void addEmployee(const Employee* e)
{
    group.emplace_back(const_cast<Employee*>(e));
}

const_cast makes it possible to form a reference or pointer to non-const type that is actually referring to a const object or a reference or pointer to non-volatile type that is actually referring to a volatile object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM