使用聚合体
聚合体就是“类的集合的类”
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Critter
{
public:
Critter(const string& name = "");
string GetName() const;
private:
string m_Name;
};
Critter::Critter(const string& name) :
m_Name(name)
{}
inline string Critter::GetName() const
{
return m_Name;
}
// 聚合体
class Farm
{
public:
Farm(int spaces = 1);
void Add(const Critter& aCritter);
void RollCall() const;
private:
vector<Critter> m_Critters; // 容器数据成员
};
Farm::Farm(int spaces)
{
m_Critters.reserve(spaces);
}
void Farm::Add(const Critter& aCritter)
{
m_Critters.push_back(aCritter);
}
void Farm::RollCall() const
{
for (vector<Critter>::const_iterator iter = m_Critters.begin();
iter != m_Critters.end();
++iter
)
{
cout << iter->GetName() << " here.\n";
}
}
int main()
{
Critter crit("Poochie");
cout << "My critter's name is " << crit.GetName() << endl;
cout << "Creating critter farm.\n";
Farm myFarm(3);
cout << "\nAdd three critters to the farm.\n";
myFarm.Add(Critter("Moe"));
myFarm.Add(Critter("Larry"));
myFarm.Add(Critter("Curly"));
cout << "\nCalling Roll...\n";
myFarm.RollCall();
return 0;
}