2017-07-24 56 views
0

我正在進行網站中的示例測試: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 
+2

不知道如果它解決了問題,但對於一個你應該清理由'刪除[答案]回答'而不是'刪除答案'(和'次'相同) – CompuChip

+0

作爲一個附註,你應該在你的代碼中進行邊界檢查。調用'getAnswer(-1);'此刻是未定義的行爲。 – IlBeldus

回答

2

你應該使用delete []而不是delete解除分配動態數組。

而且,你似乎沒有使用派生類,但儘管如此,在MultipleChoiceTest析構函數應該是虛擬

+0

我還補充說,最好是使用'std :: vector answers',以避免手動內存分配/釋放。 –

+0

@IIBeldus如何獲得MultipleChoiceTest作爲虛擬? –

+0

這兩個類中都有* no *虛函數,所以它們很可能不會多形地使用。在這種情況下,虛擬析構函數並不重要。 –