c++ - 如何利用一个函数的指针到另一个函数?
问题描述
我现在正在开发 Nim 游戏,在这里我会直截了当。我有一个定义了“player1”和“player2”的函数,我想在另一个函数中使用它们。这是它们都被定义的函数:
void ScoreKeeperInfo::welcome() {
cout << "Welcome to the Game of Nim.\n\nWhat is your name? ";
cin >> playerName;
Player player1 = new PlayerInfo(playerName);
Player player2 = new AutomatedPlayerInfo("HAL 9000", new IntermediateStrategyInfo);
cout << "Number of wins for " << player1->getName() << ": " << numberOfWinsPlayer << endl;
cout << "Number of wins for HAL 9000: " << numberOfWinsCPU << endl;
}
我在这里尝试在此函数中使用它们,其中显示“ Game game = new GameInfo(player1, player2, state) ”:
void ScoreKeeperInfo::playRepeatedly() {
int pile1 = Utils::generateRandomInt(6, 12);
int pile2 = Utils::generateRandomInt(6, 12);
int pile3 = Utils::generateRandomInt(6, 12);
string userInput;
GameState state = new GameStateInfo(pile1, pile2, pile3);
string stateDisplay = state->toString();
if (playerFirst == true) {
Game game = new GameInfo(player1, player2, state);
Player winner = game->play();
cout << winner->getName() << " wins.\n";
我有这个类的头文件:
class ScoreKeeperInfo {
public:
void start();
private:
Player player1, player2;
int numberOfWinsPlayer = 0;
int numberOfWinsCPU = 0;
bool playerFirst;
string playerName;
void welcome();
void flipCoin();
void playRepeatedly();
void restart();
};
#endif /* SCOREKEEPER_H */
然后我使用 typedef 来声明 Player 指针:
typedef class MoveInfo* Move;
typedef class GameStateInfo* GameState;
typedef class PlayerInfo* Player;
typedef class AutomatedPlayerInfo* AutomatedPlayer;
typedef class StrategyInfo* Strategy;
typedef class IntermediateStrategyInfo* IntermediateStrategy;
typedef class GameInfo* Game;
typedef class ScoreKeeperInfo* ScoreKeeper;
当我尝试使用超出范围的 player1 和 player2 指针时,我能得到一个指向哪里的指针(坏双关语)吗?第一个函数中的“player1->getName()”输出的正是我想要的,我在第二个代码块中需要它。
谢谢!
解决方案
我弄清楚了这个问题。我不得不从 player1 和 player2 声明中删除 Player。
推荐阅读
- python - 添加 CSS 文件后出现黑屏
- php - PHP7.3:如何在不在子类中重新声明的情况下,继承具有最大可能范围的受保护静态属性?
- mysql - 根据项目从两个 sql 表中求和和差异 - laravel
- css - 在 Safari 中垂直拉伸的图像,父容器作为 display flex
- c++ - 我应该将结构用作 C++ 中的参数化构造函数吗?
- android - 如何为电子商务 Android 应用程序制作管理面板或管理应用程序
- php - 有很多列的 SQL 的另一种解决方案吗
- php - 在 NGINX 服务器上运行多个 CakePHP 项目
- excel - 为什么 Excel 2016 VBA 代码在使用几次后会崩溃?
- scala - Spark 中多个 DataFrame 的并行写入