所谓类的组合是指:类中的成员数据是另一个类的对象或者是另一个类的指针或引用。通过类的组合可以在已有的抽象的基础上实现更复杂的抽象。 例如:
1、按值组合
#include<iostream.h>
#include<math.h>
class Point
{
public:
Point(int xx,int yy)//构造函数
{
x=xx;
y=yy;
cout<<"Point's constructor was called"<<endl;
}
Point(Point &p);//拷贝构造函数
int GetX(){return x;
int GetY(){return y;}
~Point()
{
cout<<"Point's destructor was called"<<endl;
}
private:
int x,y;
};
Point::Point(Point &p)
{
x=p.x;
y=p.y;
cout<<"Point's copyConstructor was called"<<endl;
}
class Distance
{
private:
Point p1,p2; //按值组合,将类Point的对象声明为类Distance的数据成员
double dist;
public:
Distance(Point a,Point b);//包含Point类
double GetDis(void)
{
return dist;
}
~Distance()
{
cout<<"Distance's destructor was called"<<endl;
}
};
Distance::Distance(Point a,Point b):p1(a),p2(b)
{
double x=double(p1.GetX()-p2.GetX());
double y=double(p1.GetY()-p2.GetY());
dist=sqrt(x*x+y*y);
cout<<"Distance's constructor was called"<<endl<<endl;
}
void main()
{
Point myp1(1,1),myp2(4,5);
Distance myd(myp1,myp2);
cout<<'\n'<<"the distance is: "<<myd.GetDis()<<endl<<endl;
}
2、按引用组合
class ZooAnimal
{
public:
// ....
private:
Endangered *_endangered1 ; //按指针组合
Endangered &_endangered2 ; //按引用组合
};
另外再看一个例子:
如果鸟是可以飞的,那么鸵鸟是鸟么?鸵鸟如何继承鸟类?[美国某著名分析软件公司2005年面试题]
解析:如果所有鸟都能飞,那鸵鸟就不是鸟!回答这种问题时,不要相信自己的直觉!将直觉和合适的继承联系起来还需要一段时间。
根据题干可以得知:鸟是可以飞的。也就是说,当鸟飞行时,它的高度是大于0的。鸵鸟是鸟类(生物学上)的一种。但它的飞行高度为0(鸵鸟不能飞)。
不要把可替代性和子集相混淆。即使鸵鸟集是鸟集的一个子集(每个驼鸟集都在鸟集内),但并不意味着鸵鸟的行为能够代替鸟的行为。可替代性与行为有关,与子集没有关系。当评价一个潜在的继承关系时,重要的因素是可替代的行为,而不是子集。
答案:如果一定要让鸵鸟来继承鸟类,可以采取组合的办法,把鸟类中的可以被鸵鸟继承的函数挑选出来,这样鸵鸟就不是“a kind of”鸟了,而是“has some kind of”鸟的属性而已。代码如下:
#include<string>
#include<iostream>
using namespace std;
class bird
{
public:
void eat()
{
cout<<"bird is eating"<<endl;
}
void sleep()
{
cout<<"bird is sleeping"<<endl;
}
void fly();
};
class ostrich
{
public:
eat()
{
smallBird.eat();
}
sleep()
{
smallBird.sleep();
}
private:
bird smallBird; //在这里使用了组合,且是按值组合:将bird的一个对象声明为另一类的数据成员
};
int main()
{
ostrich xiaoq;
xiaoq.eat();
xiaoq.sleep();
return 0;
}