gpt4 book ai didi

c++ - C++ 测试样本超出内存限制

转载 作者:行者123 更新时间:2023-11-28 01:45:34 25 4
gpt4 key购买 nike

我正在站点中进行示例测试:https://www.testdome.com/for-developers/solve-question/9808我分别为基类和派生类添加了两个析构函数来释放构造函数分配的内存。这道题的前两个要求都成功解决了,但是结果却失败了:Using timed multiple choice test as multiple choice test: Memory limit exceeded

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

#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

最佳答案

您应该使用 delete [] 而不是 delete 来释放动态数组。

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

关于c++ - C++ 测试样本超出内存限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45279719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com