57|57 - Abstract Classes and Pure virtual Functions

1. #include using namespace std; class Enemy { public: virtual void attack() { cout << "i am the enemy class" << endl; } }; class Ninja :public Enemy { public: void attack() { cout << "ninja attack!" << endl; } }; class Monster :public Enemy { public:}; int main() { Ninja n; Monster m; Enemy *enemy1 = &n; Enemy *enemy2 = &m; enemy1->attack(); enemy2->attack(); system("pause"); return 0; } 2. #include using namespace std; class Enemy { public: virtual void attack() = 0; }; class Ninja :public Enemy { public: void attack() { cout << "ninja attack!" << endl; } }; class Monster :public Enemy { public: void attack() { cout << "mponster attack!" << endl; } }; int main() { Ninja n; Monster m; Enemy *enemy1 = &n; Enemy *enemy2 = &m; enemy1->attack(); enemy2->attack(); system("pause"); return 0; }

    推荐阅读