我正試圖在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