xString 中的空指针无效

invalid null pointer in xstring

本文关键字:无效 空指针 xString      更新时间:2023-10-16

所以我几乎完成了这个作业,但现在我又遇到了困难。当我尝试从问题类中绘制文本时,我从 xstring 中得到无效的空指针。 我有大约 2 个小时,所以任何帮助将不胜感激

这是问题类:

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);

任何帮助将不胜感激!

你的运算符=(const Question&)是错误的,它除了返回当前对象之外什么都不做。如果该对象是使用默认构造函数创建的,则不会初始化"问题"和"答案",并且如果使用此运算符,程序可能会崩溃。

运算符"="应该复制每个字段。对于像"question"和"answerswer"这样的字符串指针,你需要为字符串内容分配新的内存,并从作为参数传递的对象的字符串中复制字符。但是你可能应该去掉运算符=,并使用std::string来表示"question"和"answerswer"而不是char*(见下文)。

最后

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;
    ...