简体   繁体   English

如何在指针向量上使用 push_back()?

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

I have a Manager class.我有一个Manager class。 I made an addEmployee() method to add Employee objects to it by address:我创建了一个addEmployee()方法,通过地址向其中添加Employee对象:

#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.我想既然group是一个vectorpush_back()方法应该可以工作,但它不工作。

I cannot edit the main() function.我无法编辑main() function。

What is the problem??问题是什么??

Your addEmployee() was expecting a const Employee*.您的 addEmployee() 期待一个 const Employee*。 But your vector is storing an Employee* resulting in pushback failure.但是您的向量正在存储一个 Employee* 导致回推失败。 So change your addEmployee() as follows:所以改变你的 addEmployee() 如下:

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:如果还想保留 const 指针,可以修改 Addemployee function 如下:

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. const_cast 可以形成一个指向实际上是指 const object 的非 const 类型的引用或指针,或一个指向实际上是指易失性 object 的非易失性类型的引用或指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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