我正在進行網站中的示例測試:https://www.testdome.com/for-developers/solve-question/9808 我爲基類和派生類分別添加了兩個析構函數以釋放由構造函數分配的內存。這個問題的前兩個要求是成功解決,但結果失敗,因爲:使用定時多項選擇測試作爲多項選擇測試:超過內存限制在C++測試示例中超出內存限制
我修改後的代碼,如果您可以幫助修復失敗...
#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
不知道如果它解決了問題,但對於一個你應該清理由'刪除[答案]回答'而不是'刪除答案'(和'次'相同) – CompuChip
作爲一個附註,你應該在你的代碼中進行邊界檢查。調用'getAnswer(-1);'此刻是未定義的行爲。 – IlBeldus