一、源代码:
#include<iostream>
#include<list>
#include<memory>
using namespace std;
class Employee
{
public:
Employee(string name,string dept,int salary)
{
this->_name = name;
this->_dept = dept;
this->_salary = salary;
}
void add(Employee e)
{
subordinates.push_back(e);
}
list<Employee> getSubordinates()
{
return subordinates;
}
string getString()
{
return ("Employee:[Name: "+_name+",dept: "+_dept+",salary: "+to_string(_salary)+"]");
}
private:
string _name;
string _dept;
int _salary;
list<Employee> subordinates;
};
int main()
{
shared_ptr<Employee> CEO = make_shared<Employee>("John","CEO",30000);
shared_ptr<Employee> headSales = make_shared<Employee>("Robert","Head Sales",20000);
shared_ptr<Employee> headMaketing = make_shared<Employee>("Michel","Head Maketing",20000);
shared_ptr<Employee> clerk1 = make_shared<Employee>("Laura","Maketing",10000);
shared_ptr<Employee> clerk2 = make_shared<Employee>("Bob","Maketing",10000);
shared_ptr<Employee> salesExecutive1 = make_shared<Employee>("Richard","Sales",10000);
shared_ptr<Employee> salesExecutive2 = make_shared<Employee>("Rob","Sales",10000);
headSales->add(*salesExecutive1);
headSales->add(*salesExecutive2);
headMaketing->add(*clerk1);
headMaketing->add(*clerk2);
//必须从下层往上层add,最后执行顶层CEO->add,思考一下
CEO->add(*headSales);
CEO->add(*headMaketing);
cout<<CEO->getString()<<endl;
for(auto& headEmployee:CEO->getSubordinates())
{
cout<<headEmployee.getString()<<endl;
for(auto& employee:headEmployee.getSubordinates())
{
cout<<employee.getString()<<endl;
}
}
}
二、运行结果: