C ++测试样本中超出了内存限制

时间:2017-07-24 11:41:10

标签: c++

我正在网站上进行示例测试:https://www.testdome.com/for-developers/solve-question/9808 我分别为基类和派生类添加了两个析构函数,以释放构造函数分配的内存。此问题的前两个要求是成功解决,但结果失败为:使用定时多项选择测试作为多项选择测试:超出内存限制

我修改后的代码如下所示,如果您能帮助修复失败,我将不胜感激......

#include <iostream>
#include <string>

class MultipleChoiceTest
{
public:
    MultipleChoiceTest(int questionsCount)
    {
        this->questionsCount = questionsCount;
        answers = new int[questionsCount];
        for (int i = 0; i < questionsCount; i++)
        {
            answers[i] = -1;
        }
    }

    void setAnswer(int questionIndex, int answer)
    {
        answers[questionIndex] = answer;
    }

    int getAnswer(int questionIndex) const
    {
        return answers[questionIndex];
    }
    ~MultipleChoiceTest()
    {
        delete answers; // release memory
    }
protected:
    int questionsCount;

private:
    int* answers;
};

class TimedMultipleChoiceTest : public MultipleChoiceTest
{
public:
    TimedMultipleChoiceTest(int questionsCount)
        : MultipleChoiceTest(questionsCount)
    {
        times = new int[questionsCount];
        for (int i = 0; i < questionsCount; i++)
        {
            times[i] = 0;
        }
    }

    void setTime(int questionIndex, int time)
    {
        times[questionIndex] = time;
    }

    int getTime(int questionIndex) const
    {
        return times[questionIndex];
    }
    ~TimedMultipleChoiceTest()
    {
        delete times; // release memory
    }
private:
    int* times;
};

#ifndef RunTests
void executeTest()
{
    MultipleChoiceTest test(5);
    for (int i = 0; i < 5; i++)
    {
        test.setAnswer(i, i);
    }

    for (int i = 0; i < 5; i++)
    {
        std::cout << "Question " << i + 1 << ", correct answer: " << test.getAnswer(i) << "\n";
    }
}

int main()
{
    for (int i = 0; i < 3; i++)
    {
        std::cout << "Test: " << i + 1 << "\n";
        executeTest();
    }
}
#endif  

1 个答案:

答案 0 :(得分:2)

您应该使用delete []而不是delete来取消分配动态数组。

此外,您似乎没有使用派生类,但是,MultipleChoiceTest中的析构函数应该是虚拟的