2013-11-27 85 views
-1

我正试图在C++中实现模式状态。C++中的模式状态

我有我的客户:球员 国家作为接口 和2状态:In和Out

这是我in.h中:

#ifndef ODA_IN_H 
#define ODA_IN_H 

#include <vector> 
#include "Player.h" 
#include "Hand.h" 

using namespace std; 

class In : public State { 
    public: 
     In(Player* player); 
     void doYouChange(); 
     Card throwCard(int i); 
     void showHand(); 
     void setHand(vector<Card> &other); 

    private: 
     Player* player; 
     Hand hand; 
}; 

#endif 

而且In.cpp:

#include <iostream> 
#include "In.h" 

using namespace std; 

In::In(Player* player) { 
    this->player = player; 
    cout << player->getName() <<endl; 
} 
void In::doYouChange() { 
    string sth; 
    do { 
     cout << player->getName() << ", Do you want to leave for this round?(Yes/No)?"; 
     cin >> sth; 
    } while (sth != "No" && sth != "Yes"); 
    if (sth == "Yes") { 
     player->setState(player->getOut()); 
    } 
} 
Card In::throwCard(int i) { 
    Card c = hand.getCard(i); 
    return c; 
} 
void In::showHand() { 
    hand.showHand(); 
} 
void In::setHand(vector<Card> &other) { 
    hand.setHand(other); 
} 

因此,构造函数可以写出名称,而doYouChange()方法没有。而后来它完全打破任何消息只是内存垃圾:/

我所说的doYouChange()从其他类这样的:

for (int i = 0; i < playersNb; ++i) { 
    players[i].doYouChange(); 
} 

的第一个球员还好没有名称,第二它打破。

我完全不知道。我试图重新实现,但没有任何帮助。

/* ** * ** * ** * ** * ** */ UPDATE: 创建一个播放器(如图案状态的客户端在构造函数中,我也初始化状态):

Player::Player(string n) { 
    name = n; 
    out = new Out(this); 
    in = new In(this); 
    this -> state = in; 
} 

而在与相同的类由于该player变为无效的事实(/破坏)

players.push_back(Player(name)); 
+0

听起来像你有东西指向未初始化/释放内存。你尝试在调试器中运行吗?你在写什么平台,以便我们可以推荐工具。 – Rob

+0

我正在写Sublime,并在终端中使用g ++。 任何可以帮助我调试的工具都会有所帮助! – Judit

+0

你有安装gdb吗?它是一个用于C++的开源调试器。 (https://www.gnu.org/software/gdb/) – Rob

回答

0

这个错误很可能会occure:加我在构造函数中的球员。 考虑下面的代码:

Player* player = new Player(); 

In inState(player); // will work 
inState->doYouChange(); // will work 

delete player; 

inState->doYouChange(); // wont work 

如果没有更多的细节,我们不能给你一个具体的解决方案,但只是一般的建议:

  • 确保您知道谁管理您player对象
  • 检查情况在这些物体被破坏的地方,试图断定它们,你的物体是否真的被破坏?
  • 断点doYouChange()方法,并检查player对象
  • 考虑使用智能指针来克服所有权问题:请参见std::shared_ptr(也有很多其他的图书馆在那里它可以提供智能指针更好地相适应您的需求,如波苏或加速)
+0

我不删除播放器。其实它写出如果我想改变?但不是名称。所以它被调用。 cout << player-> getName()<<“,你想离开这一轮?(是/否)?”; – Judit

+0

将“std :: endl”附加到该语句。我坚信说它不会执行。如果你删除'player',指针仍然保存一个内存地址,如果你访问'getName()',它会返回你现在在那个内存位置上的垃圾,你描述的行为。假设'getName()'实际返回一个'char *',如果返回的char *指向一个值为0x00(null-termination)的位置,则不会打印任何内容。这同样适用于'std :: string'(但它很难解释)。没有进一步的信息/代码它不可能告诉你我的问题 – Paranaix

+0

我补充说。 它打印出来:“,你想离开这一轮?(是/否)?”所以这里只是空的。之后它返回到for。当i = 1时,它会抛出垃圾。 如果你告诉我,我会附上任何有用的东西。但我不知道我还应该附加什么。 – Judit