2011-05-17 31 views
0

所以我幾乎完成了這個任務,但現在我又遇到了困難。當我嘗試從問題類中繪製文本時,我從xstring獲得無效的空指針。我有大約2個小時,所以任何幫助真的理解xstring中的無效空指針

這裏的問題類:

class Question { 

public: 
    int col; 
    int row; 
    bool dailyDouble; 
    char* question; 
    char* answer; 
    double value; 
    Question(); 
    Question(int, int, bool, char*, char*); 
    bool checkAnswer(string); 
    Question& operator=(const Question&); 
}; 



Question::Question() {} 

Question::Question(int c, int r, bool d, char* q, char* a) 
{ 
    col = c; row = r; dailyDouble = d; question = q, answer = a; 
    if(d) 
     value = r * 200 * 2; 
    else 
     value = r * 200; 
} 

bool Question::checkAnswer(string answer) 
{ 
    if(answer.find("What is") && answer.find(answer)) 
     return true; 
    return false; 
} 

Question& Question::operator=(const Question&) 
{ 
    return *this; 
} 

我有一個畫文本方法(的作品),但我跑出來的空間,所以這是導致錯誤的行:

drawText((WinWidth/2)-200,(WinHeight/2) - 100, curQuestion.question); 

任何幫助將真正感激!

+1

運行在哪裏的房間? SO編輯器滾動,你知道! – 2011-05-17 10:13:10

+5

什麼是詢問?指針在哪裏?在調試器中運行應用程序,並在它聲明時按下重試按鈕。它會帶你到問題的路線。你可以檢查Call Stack窗口來查看調用堆棧中的以前方法 – 2011-05-17 10:14:12

回答

1

您的操作員=(常量問題&)是錯誤的,它什麼都不做,只是返回當前對象。如果該對象是使用默認構造函數創建的,則「問題」和「答案」未初始化,並且如果使用此運算符,程序可能會崩潰。

運算符「=」應該複製每個字段。對於像「question」和「answer」這樣的字符串指針,您需要爲字符串內容分配新的內存,並將作爲參數傳遞的對象字符串中的字符複製。但是你可能應該去掉operator =無論如何,使用std :: string代替char *(見下面)的「question」和「answer」。

最後,

if(answer.find("What is") && answer.find(answer)) 

沒有道理。它可能應該是這樣的:

bool Question::checkAnswer(string proposedAnswer) 
{ 
    if(question.find("What is") && answer.find(proposedAnswer)) 
     return true; 
    return false; 
} 

...假設你從char *更改問題和答案的類型爲字符串:

public: 
    int col; 
    int row; 
    bool dailyDouble; 
    string question; 
    string answer; 
    ... 
+0

operator =(const Question&)是我從本網站上的另一個問題得到的,這就是我在這種情況下需要做的。遊戲基於Jeopardy,這就是爲什麼checkAnswer檢查提出的答案,以確保它處於危險的格式並且有正確的答案。但是,問題是我的問題和答案是char *,現在已經修復了。謝謝。 – CaffeinatedCM 2011-05-17 19:54:56