如图关于如何实现上图图中的几种关系,最近我写的一个小程序,希望大家多多指点:
/************************************************************************/
/* 课程科目:软件工程 作者邮箱:juste0830@126.com */
/* 开发环境:VC6.0 编写日期: 2012年11月10日晨 */
/***********************************************************************/
#include <iostream.h>
/************定义水类*****************/
class water
{
//关于水的属性和操作
public:
char provide_need2; //水提供生命存的一个需求之一
char provide_need1; //水提供生命存的一个需求之一
};
/************定义翅膀类*****************/
class wing
{
public:
friend class bird;
private:
wing()
{
cout<<"有翅膀-";
}
};
/************定义气候类*****************/
class climate
{
public:
void show()
{
cout<<"气候适宜,";
}
};
/************定义动物类*****************/
class animal
{
private:
char have_live; //有生命
char need1;
char need2;
public:
animal(const water& w)
{
need1=w.provide_need1;
need2=w.provide_need2;
}
void multiply() //繁殖
{
cout<<"-能繁殖"<<endl;
}
};
/************定义鸟类*****************/
class bird:public animal //继承关系
{
public:
wing theWing;
bird(water& w):animal(w)
{
}
void lay_egg()
{
cout<<"下蛋"<<endl;
}
private:
char have_feather; //有羽毛
char have_no_tooth; //没有牙齿
};
/************定义大雁类*****************/
class goose :public bird
{
public:
goose(water& w):bird(w)
{
}
};
/************定义雁群类*****************/
class geese
{
public:
goose g1; //雁群有大雁组成
goose g2;
};
/************定义企鹅类*****************/
class penguin :public bird
{
public:
penguin(water &w):bird(w)
{
}
void Live(climate CL)
{
CL.show();
cout<<"企鹅生存下来"<<endl;
}
};
int main()
{
water theWater;
//animal theAnimal; //这里会出现错误,因为没有水,动物就不能生存------------------依赖关系
animal theAnimal(theWater);//给与了水,动物才能存在(被创建)
cout<<"这是个鸟:";
bird bird1(theWater); //鸟继承与动物,因此鸟也依赖水,没水不能有鸟的创建
bird1.multiply(); //在bird中没有定义有生命,但是它继承了父类animal--------------继承关系
penguin thePenguin(theWater);
climate theClimate;
//thePenguin.Live();//没有合适的气候,企鹅就不能生存
thePenguin.Live(theClimate);//存在依赖,继承,还有关联-----------------------------关联关系
//wing theWing; //翅膀不能被单独定义,只能在鸟存在时,翅膀才能存在-----------------组合关系
cout<<"这是大雁:";
//如果不定义大雁类,雁群类将无法定义。也就是说,如果不存在大雁,就不存在雁群
goose theGoose(theWater);// 但是大雁可以单独存在--------------------------- -------聚合关系
cout<<"\n不存在大雁,就不存在雁群"<<endl;
cout<<"不存在雁群,去可以存在大雁"<<endl;
cout<<endl;
return 0;
}