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
|
#include <cmath>// for sqrt()
#include <iostream>// for I/O
using namespace std;
// base class
class character
{
public:
float x;
float y;
float dist( const character& c ){ return sqrt( (x-c.x)*(x-c.x) + (y-c.y)*(y-c.y) ); }
float dist( const character* pc ){ return sqrt( (x-pc->x)*(x-pc->x) + (y-pc->y)*(y-pc->y) ); }
virtual void showMe(void){ cout << "Character"; }// derived objects define what this means in their context
void showUs( character* pc )
{
cout << "Caller is :"; this->showMe(); cout << endl;
cout << "Passed is :"; pc->showMe(); cout << endl << endl;
}
// constructor
character(float X, float Y): x(X), y(Y){}
};
class enemy: public character
{
int E1;// some property
public:
enemy(int e1, float X, float Y): E1(e1), character(X, Y){}
void showMe(void){ cout << "Enemy"; }
};
class player: public character
{
int P1;// some property
int P2;// another property
public:
player(int p1, int p2, float X, float Y): P1(p1), P2(p2), character(X, Y){}
void showMe(void){ cout << "Player"; }
};
int main(void)
{
character cA( 5.0f, 5.0f );
enemy eA( 1, 0.0f, 0.0f ), eB( 2, 3.0f, 4.0f );
player pA( 3, 4, 1.0f, 1.0f ), pB( 5, 6, 2.0f, 3.0f );
// mix derived types in base function call
cout << "distance between enemies = " << eA.dist( eB ) << endl;
cout << "distance between pA and eB = " << pA.dist( eB ) << endl;
// again using base pointers
character* pChars[] = { &cA, &eA, &eB, &pA, &pB };
cout << "distance between characters 1 and 3 = " << pChars[1]->dist( pChars[3] ) << endl << endl;
// virtual function calls using base pointers
pChars[0]->showUs( pChars[4] );// character and player
pChars[1]->showUs( pChars[2] );// 2 enemies
pChars[3]->showUs( pChars[2] );// player and enemy
cout << endl;
return 0;
}
|