1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream>
using namespace std;
class Lion;
class Zebra;
class Animal
{
public:
virtual ~Animal(){}
virtual int type() {return 0;}
void meet(Animal * a)
{
int type1=type();
int type2=a->type();
if (meet_ftable[type1][type2]==0)
cout << "undefined behavior!..." << endl;
else
meet_ftable[type1][type2](this,a);
}
private:
typedef void (*meet_func)(Animal *,Animal*);
static const meet_func meet_ftable[3][3];
static void lion_lion(Animal*,Animal*)
{
cout << "a lion meets another lion." << endl;
}
static void zebra_zebra(Animal*,Animal*)
{
cout << "a zebra meets another zebra." << endl;
}
static void lion_zebra(Animal*,Animal*)
{
cout << "a lion meets a zebra. ";
cout << "lucky lion!" << endl;
}
static void zebra_lion(Animal*,Animal*)
{
cout << "a zebra meets a lion. ";
cout << "poor zebra..." << endl;
}
};
const Animal::meet_func Animal::meet_ftable[3][3]=
{
0, 0, 0,
0, Animal::lion_lion, Animal::lion_zebra,
0, Animal::zebra_lion, Animal::zebra_zebra
};
class Lion: public Animal
{
virtual int type() {return 1;}
};
class Zebra: public Animal
{
virtual int type() {return 2;}
};
int main()
{
Animal a;
Lion lion;
Zebra zebra;
Animal * pa = &a;
Animal * pa1 = &lion;
Animal * pa2 = &zebra;
lion.meet(pa1);
pa2->meet(&zebra);
pa1->meet(pa2);
zebra.meet(&lion);
a.meet(pa1);
pa->meet(&zebra);
cout << "\nhit enter to quit...";
cin.get();
return 0;
}
|