xstring中的无效空指针 [英] invalid null pointer in xstring

查看:1229
本文介绍了xstring中的无效空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我几乎完成了这项任务,但现在我又有困难了。当我尝试从问题类绘制文本时,我从xstring获取无效的空指针。我有大约2小时,所以任何帮助真的会感激。

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

这里是问题类:

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!

推荐答案

您的operator =(const Question&)是错误的,它不会返回当前对象。如果使用默认构造函数创建了该对象,则不会初始化question和answer,并且如果使用此运算符,您的程序可能会崩溃。

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.

=应该复制每个字段。对于像question和answer这样的字符串指针,您需要为字符串内容分配新的内存,并从作为参数传递的对象的字符串中复制字符。但你可能应该摆脱operator =反正,并使用std :: stringquestion和answer而不是char *(见下文)。

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

最后,

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

...假设您将问题和答案的类型从char *更改为string:

... assuming you changed the type of question and answer from char* to string:

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

这篇关于xstring中的无效空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆