对象之间的C ++共享变量。 [英] C++ Sharing variable between objects.

查看:79
本文介绍了对象之间的C ++共享变量。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个小问题,我希望两个不同的类能够共享并更改另一个类对象。

I'm having a little problem where I want two different classes to be able to share and make changes to another class object.

我有一个HumanPlayer类,一个ComputerPlayer类和一个Board类。两个玩家类别需要能够与一个Board类别进行交互。我以为我可以将对同一Board对象的引用传递给每个类,但是它似乎并没有达到我想要的方式。这是主要内容的一部分,我将尽力描述正在发生的事情:

I've got a HumanPlayer class, a ComputerPlayer class, and a Board class. The two player classes need to be able to interact with the one Board class. I thought that I could pass a reference to the same Board object to each class but it doesn't appear to be working the way I want it to. Here's part of what's in main and I'll describe what's happening as best I can:

// main.cpp

//main.cpp

    Board *board2 = new Board();
    board2->setBoardSize(5); 
    board2->initPits(); 

    HumanPlayer firstPlayer(*board2, *menu, menu->askForFirstTurn(), true); 

    firstPlayer.removeFromPit(3);  

    board2->showBoard();

firstPlayer.removeFromPit(3); 是应该只是将board类的数组中的值设置为零。它做到了。如果我要从FirstPlayer类的代码中显示木板,它将显示更改。但是,当我调用 board2-> showBoard()时,好像什么都没有改变。仍然是原始的未更改板。我真正想发生的事情是让我的firstPlayer和secondPlayer类在一个共享的board对象上工作。我只是不确定现在如何正确实施。

firstPlayer.removeFromPit(3); is supposed to just set a value in an array in the board class to zero. And it does that. If I were to show the board from within the code of the FirstPlayer class, it would show the change. But when I call board2->showBoard() it's as if nothing was changed. It's still the original unchanged board. What I really want to have happen is to have my firstPlayer and secondPlayer classes work on one shared board object. I'm just not sure how to implement this properly now.

谢谢大家的帮助。如果您需要更多信息,请与我们联系。

Thank you all for your help. Let me know if you need more information.

推荐答案

听起来您正在复制板对象,而不是通过引用传递它。玩家类的构造函数应如下所示:

It sounds like you are copying the board object instead of passing it by reference. The constructor of your player classes should look like this:

class Player
{
public:
    Player(Board& board) // REFERENCE TO Board
       : the_board_(board) // initialize the reference
    {
    }

protected:
   Board& the_board_;  // REFERENCE to Board
};

如果您缺少& 运算符任何地方(在构造函数签名中或在类成员变量上),您都将复制将在您的类中使用的木板。

If you are missing the & operator anywhere (either in the constructor signature or on the class member variable) then you will make a copy of the board that will be used within your class.

这篇关于对象之间的C ++共享变量。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆