0

そこで、スコアボードと 2 人のプレーヤーを持つプログラムを実装しようとしています。シングルトン パターンを使用して、2 人のプレーヤーがスコアボードを共有するようにしようとしています。ただし、プレーヤー クラスで定義されたグローバル スコアボードでメソッドを使用しようとすると、常に「実行に失敗しました」というメッセージが表示されます。

これらは私の 2 つのヘッダー ファイルです。必要に応じて、完全な実装を提供できます。

#ifndef PLAYER_H
#define PLAYER_H
#include "scoreboard.h"
#include <string>
#include <fstream>


class Player{
private:
        std::ifstream file1;
        std::ifstream file2;
        static Scoreboard* _game;
    public:
        static Scoreboard* Game();
        void makeMove(const char,const std::string);
};


#endif

#ifndef SCOREBOARD_H
#define SCOREBOARD_H

class Scoreboard{
    private:
        int aWin;
        int bWin;
        int LIMIT;
        int curCounter;

    public:
        void resetWins();
        void addWin(char);
        void makeMove(const int, char);
        void startGame(const int, const int);
        int getWin(char);
        int getTotal();
        int getLimit();
};

#endif  /* SCOREBOARD_H */

player.ccで

Scoreboard* Player::_game = 0;

Scoreboard* Player::Game(){
    if (_game = 0)
    {
        _game = new Scoreboard;
        _game->resetWins();
    }
    return _game;
} 

makeMove メソッドとともに

4

2 に答える 2

1

インスタンスはポインターである必要はありませScoreboardん。

static Scoreboard _game;
// ...
static Scoreboard& Game() { return _game; }

または、次のクラス宣言を省略し_gameます。

// you can either make this function static or non-static
Scoreboard& Game()
{
    static Scoreboard game; // but this variable MUST be static
    return game;
}

これは、メモリ管理の問題なしで同じことを行います。

Scoreboardこれにより、 for allの単一のインスタンスが作成されますPlayersの1 つのインスタンスのみが必要なScoreboard場合 (たとえばReferees、スコアボードも表示する必要があるクラスがある場合)、スコアボード クラスを次のように変更します。

class Scoreboard
{
private:
    // all your data members
    Scoreboard() {} // your default constructor - note that it is private!
public:
    // other methods
    Scoreboard& getInstance()
    {
        static Scoreboard instance;
        return instance;
    }
};

次に、他のクラスでそれにアクセスするには、スコアボード ヘッダーを含めて、次のように使用します。

#include "Scoreboard.h"

void my_func()
{
    Scoreboard& scoreboard = Scoreboard::getInstance();
    scoreboard.DoSomething();
}
于 2013-11-01T15:11:05.213 に答える