多态的定义和多态的三个必要条件





多态发生的三个必要条件
要有继承。
要有子类重写父类的虚函数
父类指针(或者引用) 指向子类对象。
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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #define _CRT_SECURE_NO_WARNINGS #include <iostream>
using namespace std;
class Hero { public: virtual int getAd(){ return 10; } };
class SuperHero :public Hero { public: virtual int getAd() { return 100; } };
class BugHero : public Hero { public: virtual int getAd() { return 10000; } };
class Monster { public: int getAd() { return 30; } };
void PlayerFight(Hero *hero, Monster *m) { if (hero->getAd() > m->getAd()) { cout << "英雄战胜了 叫兽" << endl; } else { cout << "英雄挂了。" << endl; } }
int main(void) { Hero hero1; Monster mon1;
SuperHero hero2;
BugHero hero3;
PlayerFight(&hero1, &mon1);
PlayerFight(&hero2, &mon1);
PlayerFight(&hero3, &mon1);
int a; int*p = NULL;
p = &a;
*p;
cin >> a;
if (a > 10) { cout << a << endl; } else { cout << "a 不大于10" << endl; } return 0; }
|