我已经实现了下面的程序来理解复合设计模式。我也使用了 C++11 中的几个概念。但对我不利的是,该程序在运行时出现分段错误。我尝试使用 GDB 进行调试,发现 getID() 函数存在一些问题。
#0 0x08049a12 in Employee::getID (this=0x0) at Composite.cpp:27
27 int getID(){return ID;}
但是我仍然无法理解该功能有什么问题?感谢有人可以提供帮助。
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Employee
{
protected:
int ID;
string Name;
string Role;
public:
Employee(int empID, string empName, string empRole)
{
ID=empID;
Name=empName;
Role=empRole;
}
virtual void showDetails()=0;
virtual void addWorker(shared_ptr<Employee> newWorker)=0;
virtual void deleteWorker(shared_ptr<Employee> employee)=0;
virtual ~Employee(){}
int getID(){return ID;}
};
class Worker : public Employee
{
public:
Worker(int empID, string empName, string empRole)
: Employee(empID, empName, empRole) {}
void showDetails()
{
cout<<Name<<" ("<<ID<<") "<<Role<<endl;
}
void addWorker(shared_ptr<Employee> newWorker){};
void deleteWorker(shared_ptr<Employee> employee){};
};
class Supervisor : public Employee
{
private:
vector<shared_ptr<Employee>> myTeam;
public:
Supervisor(int empID, string empName, string empRole)
: Employee(empID, empName, empRole) {}
void addWorker(shared_ptr<Employee> newWorker)
{
myTeam.push_back(newWorker);
}
void deleteWorker(shared_ptr<Employee> employee)
{
int pos=0;
for (auto temp : myTeam)
{
if (temp->getID()!=employee->getID())
++pos;
else
myTeam.erase(myTeam.begin()+pos);
}
}
void showDetails()
{
cout<<Name<<" ("<<ID<<") "<<Role<<" ---->"<<endl;
for (auto worker : myTeam)
{
worker->showDetails();
}
cout<<endl;
}
};
int main()
{
shared_ptr<Employee> Tushar(new Worker(376653,"Tushar Shah","Team mate"));
shared_ptr<Employee> Ranjeet(new Worker(469725,"Ranjeet Aglawe","Team mate"));
shared_ptr<Employee> Kiran(new Supervisor(137581,"Kiran Asher","Manager"));
shared_ptr<Employee> Namita(new Supervisor(122110,"Namita Gawde","Manager"));
shared_ptr<Employee> Rumman(new Supervisor(122022,"Rumman Sayed","Manager"));
shared_ptr<Employee> Rajendra(new Supervisor(111109,"Rajendra Redkar","Manager"));
shared_ptr<Employee> Sameer(new Supervisor(106213,"Sameer Rajadhyax","Group Lead"));
Kiran->addWorker(Tushar);
Kiran->addWorker(Ranjeet);
Sameer->addWorker(Kiran);
Sameer->addWorker(Namita);
Sameer->addWorker(Rumman);
Sameer->addWorker(Rajendra);
Sameer->showDetails();
Sameer->deleteWorker(Rumman);
Sameer->showDetails();
return 0;
}