2013-11-27 83 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