3

我需要制作一个副本,GameMaster* thisMaster这样我就可以在保持“干净”副本的同时进行操作。但是,我现在的做法是,当我对 进行更改时copy,它也会发生变化thisMaster

void Move::possibleMoves(GameMaster* thisMaster)
{
     GameMaster* copy = new GameMaster(*thisMaster);
}

我怎样才能解决这个问题?

编辑:我创建了一个复制构造函数,但仍然遇到同样的问题。

GameMaster::GameMaster(const GameMaster& gm)
{
    for(int i=0;i<GAMETILES;i++)
    {
        gameTiles[i]=gm.gameTiles[i];
    }
    players=gm.players;
    vertLines=gm.vertLines;
    horLines=gm.horLines;
    turn = gm.turn;
    masterBoard=gm.masterBoard;
    lastLegal=gm.lastLegal;
    lastScore=gm.lastScore;
}

下面是 GameMaster 的完整类定义:

Class GameMaster
{
public:
    GameMaster(void);
    GameMaster(const GameMaster& gm);
    ~GameMaster(void);
    //functions

private:
    std::vector <Player*> players;
    std::vector <Line> vertLines;
    std::vector <Line> horLines;
    Tile gameTiles [GAMETILES];
    std::vector <std::string>colors;
    std::vector <std::string>shapes;
    int turn;
    Board masterBoard;
    bool lastLegal;
    int lastScore;
};

使用复制构造函数,我仍然遇到 Board 更改值的问题。它也需要复制构造函数吗?

4

2 回答 2

2
Class GameMaster
{
public:
    GameMaster(void);
    GameMaster(const GameMaster& gm);
    ~GameMaster(void);
    //functions

private:
    std::vector <Player*> players; // You should make a deep copy because of pointers
    std::vector <Line> vertLines; // Shallow copy is OK if Line doesn't have pointers in it
    std::vector <Line> horLines; // see above
    Tile gameTiles [GAMETILES]; // One by one assignment is OK
    std::vector <std::string>colors; // Shallow copy is OK
    std::vector <std::string>shapes; // Shallow copy is OK
    int turn; // assignment is OK
    Board masterBoard; // same questions for GameMaster still exists for copying this
    bool lastLegal; // assignment is OK
    int lastScore; // assignment is OK
};

这是浅拷贝与深拷贝的链接

于 2012-08-24T06:44:22.223 回答
0

玩家=gm.players;

只是复制指针集合..您需要对新向量中的玩家进行深度复制。

编辑

for( auto iter = gm.players.begin(); iter != gm.players.end(); ++iter) 
{
   players.push_back(new Players(*iter))
}

您还需要为 Players 提供一个副本 const。

干杯

于 2012-08-24T06:41:15.443 回答