首页 > 解决方案 > 如何利用一个函数的指针到另一个函数?

问题描述

我现在正在开发 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()”输出的正是我想要的,我在第二个代码块中需要它。

谢谢!

标签: c++classooppointers

解决方案


我弄清楚了这个问题。我不得不从 player1 和 player2 声明中删除 Player。


推荐阅读