C++ 方式:
Game.h
#include <iostream> class Game { protected: virtual void initialize() = 0; virtual void startPlay() = 0; virtual void endPlay() = 0; public: virtual void play() { initialize(); startPlay(); endPlay(); } };
Cricket.h
#include "Game.h" class Cricket : public Game { protected: virtual void initialize() { std::cout << "Cricket Game Finished!" << std::endl; } virtual void startPlay() { std::cout << "Cricket Game Initialized! Start playing." << std::endl; } virtual void endPlay() { std::cout << "Cricket Game Started. Enjoy the game!" << std::endl; } };
Football.h
#include "Game.h" class Football : public Game { protected: virtual void initialize() { std::cout << "Football Game Finished!" << std::endl; } virtual void startPlay() { std::cout << "Football Game Initialized! Start playing." << std::endl; } virtual void endPlay() { std::cout << "Football Game Started. Enjoy the game!" << std::endl; } };
Main.cpp
#include <iostream> #include "Cricket.h" #include "Football.h" int main(int argc, char* argv[]) { Game *game = new Cricket(); game->play(); std::cout << std::endl; game = new Football(); game->play(); }
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/java-jiao-cheng/10283.html