一、源代码:
#include<iostream>
#include<memory>
using namespace std;
class Game
{
public:
virtual void initialize() = 0;
virtual void startPlay() = 0;
virtual void endPlay() = 0;
virtual ~Game() = default;
void play()
{
initialize();
startPlay();
endPlay();
}
};
class Cricket:public Game
{
public:
virtual void initialize() override
{
cout<<"Cricket Game Initialized! Start playing."<<endl;
}
virtual void startPlay() override
{
cout<<"Cricket Game Started.Enjoy the game!"<<endl;
}
virtual void endPlay() override
{
cout<<"Cricket Game Finished!"<<endl;
}
};
class Football:public Game
{
public:
virtual void initialize() override
{
cout<<"Football Game Initialized! Start playing."<<endl;
}
virtual void startPlay() override
{
cout<<"Football Game Started.Enjoy the game!"<<endl;
}
virtual void endPlay() override
{
cout<<"Football Game Finished!"<<endl;
}
};
int main()
{
shared_ptr<Game> game = make_shared<Cricket>();
game->play();
cout<<endl;
game = make_shared<Football>();
game->play();
}
二、运行结果:

本文介绍了一个使用C++实现的游戏基类Game及其两个派生类Cricket和Football,通过抽象基类Game定义了游戏初始化、开始和结束的基本操作,而Cricket和Football类则具体实现了各自游戏的这些操作。
189

被折叠的 条评论
为什么被折叠?



