1.聚合关系的特征:"成员对象"可以独立于“聚合对象”而存在
2.c++中用“类(or对象)的指针”实现这个 聚合关系
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Coach
{
//定义一个教练类
public:
string name;
public:
Coach() {
this->name = "无名氏" ;//默认构造函数
};
Coach(string name_) :name(name_) {}; //1个参数构造函数
};
class Player
{
//定义一个球员类
public: string name;
public:
Player() {
this->name = "某球员";
}; //默认构造函数
Player(string name_) :name(name_) {}; //一个参数的构造函数
};
//定义一个聚合类:team
class Team
{
private:
Coach* choach_p;
vector<Player*> players;
string name;
public:
Team(Coach* c,string name_):name(name_)
{
choach_p = c; //指向那个 对象指针
} //构造函数
//分别:招募球员,更换教练,开出球员3个函数
void changeCoach(Coach* c)
{
cout << "最新消息:" << "教练 " << this->choach_p->name << " 更换为 " << c->name << endl;
choach_p = c; //更换教练
}
void employPlayer(Player *p)
{
players.push_back(p);
cout << "成功招募 球员 " << p->name << endl; //招募新球员
}
void firePlayer(Player* p)
{
//开出球员
//遍历vector寻找
for (auto it = players.begin(); it != players.end(); it++)
{
if (*it == p)
{
cout << "很遗憾,球员" << p->name << " 被宣布开除!!!" << endl;
players.erase(it); //删除对应球员的迭代器(erase里面的参数就是对应的迭代器)
cout << this->name<<" 剩余" << players.size() << "个 球员" << endl;
break;
}
}
}
};
int main()
{
//测试:
Coach* c = new Coach("张三");
Coach* c2 = new Coach("李四");
//cout << c->name << endl;
Player* p1 = new Player("球员1号");
Player* p2 = new Player("球员2号");
Team t1(c, "中大篮球队");
t1.employPlayer(p1);
t1.employPlayer(p2);
t1.firePlayer(p1);
t1.changeCoach(c2);
return 0;
}