我正试图在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));
听起来像你有东西指向未初始化/释放内存。你尝试在调试器中运行吗?你在写什么平台,以便我们可以推荐工具。 – Rob
我正在写Sublime,并在终端中使用g ++。 任何可以帮助我调试的工具都会有所帮助! – Judit
你有安装gdb吗?它是一个用于C++的开源调试器。 (https://www.gnu.org/software/gdb/) – Rob