请告诉我此代码有运行时错误的原因。 我认为addEmployee()函数有问题。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
enum EmployeeLevel {fresh, sophomore, junior, senior};
class Employee {
string name;
EmployeeLevel level;
public:
Employee(const string & _name, const EmployeeLevel _level)
: name(_name) {
level = _level;
}
Employee(const Employee & employee) {
name = employee.name;
level = employee.level;
}
void changeLevel() {
level = static_cast<EmployeeLevel> (level + 1);
}
};
class Manager: public Employee {
vector<Employee *> group;
public:
Manager(const string & _name, const EmployeeLevel _level)
: Employee(_name, _level) {}
~Manager() {
for (vector<Employee *>::iterator it = group.begin(); it != group.end(); ++it)
delete *it;
}
void addEmployee(Employee * employee) {
group.push_back(employee);
}
};
int main(void)
{
Employee e1("홍", fresh), e2("김", sophomore), e3("차", fresh);
Manager m1("Tom", senior);
m1.addEmployee(&e1);
}
如果我修改了函数(addEmployee()),如下所示,而不是错误。 但我想知道为什么使用“push_back(employee)”会出现运行时错误。
void addEmployee(Employee * employee) {
Employee * tempEmployee = new Employee(*employee);
group.push_back(tempEmployee);
}
答案 0 :(得分:0)
第一个版本崩溃的问题是你添加一个指向本地变量的指针,即编译器管理存储的对象。这意味着当Manager
被破坏时,它将尝试delete
此对象,即您未使用new
分配的对象。
只有delete
你new
(和delete[]
你new[]
)的内容!
事实上,我认为没有理由拥有指针。而是有一个普通对象的矢量,即std::vector<Employee>
。