invalid null pointer in xstring
So I'm almost done with this assignment but now I'm having difficulties again. When I try to draw text from a question class I get invalid null pointer from xstring. I have about 2 hours, so any help would really be appreciated
Here's the question class:
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;
}
I have a draw text method (that works) but I'm running out of room, so this is the line that causes the error:
drawText((WinWidth/2)-200,(WinHeight/2) - 100, curQuestion.question);
any help would really be appreciated!
Your operator=(const Question&) is wrong, it does nothing but returning the current object. If that object was created with the default constructor, "question" and "answer" are not initialized, and your program may crash if this operator is used.
The operator "=" is supposed to copy each field. For string pointers like "question" and "answer", you need to allocate new memory for the string content, and copy the characters from the strings of the object passed as a parameter. But you probably should get rid of the operator= anyway, and use std::string for "question" and "answer" instead of char* (see below).
Finally,
if(answer.find("What is") && answer.find(answer))
Does not make sense. It should probably be something like:
bool Question::checkAnswer(string proposedAnswer)
{
if(question.find("What is") && answer.find(proposedAnswer))
return true;
return false;
}
... assuming you changed the type of question and answer from char* to string:
public:
int col;
int row;
bool dailyDouble;
string question;
string answer;
...
精彩评论