2013-04-05 142 views
0
#include <iostream> 

    class MyClass 
    { 
     public: 
      MyClass() { 
       itsAge = 1; 
       itsWeight = 5; 
      } 

      ~MyClass() {} 
      int GetAge() const { return itsAge; } 
      int GetWeight() const { return itsWeight; } 
      void SetAge(int age) { itsAge = age; } 

     private: 
      int itsAge; 
      int itsWeight; 

    }; 

    int main() 
    { 
     MyClass * myObject[50]; // define array of objects...define the type as the object 
     int i; 
     MyClass * objectPointer; 
     for (i = 0; i < 50; i++) 
     { 
      objectPointer = new MyClass; 
      objectPointer->SetAge(2*i + 1); 
      myObject[i] = objectPointer; 
     } 

     for (i = 0; i < 50; i++) 
      std::cout << "#" << i + 1 << ": " << myObject[i]->GetAge() << std::endl; 

     for (i = 0; i < 50; i++) 
     { 
      delete myObject[i]; 
      myObject[i] = NULL; 
     } 

我想知道爲什麼objectPointer必須在for循環中,如果我將它取出並放在for循環之前,我會得到無意義的結果。幫助將不勝感激,謝謝...抱歉可怕的格式。對象的動態內存分配

+1

你的意思是你會得到無意義的結果,因爲它現在是?你在'for'循環之前定義'objectPointer'。 – 2013-04-05 16:14:10

+0

@sftrabbit他顯然意味着assigment'objectPointer = new MyClass;' – Paranaix 2013-04-05 16:22:04

回答

2
myObject[i] = objectPointer; 

它應該是在循環中,因爲你是存儲指針數組中的一個新的參考。如果它在循環之外,那麼所有指針數組指向相同的引用。在這種情況下,由於所有指針數組都指向相同的內存位置,所以在釋放時應該小心。

+0

我不確定他在說什麼,因爲我不知道哪一行代碼「必須在for循環中」? – 2013-04-05 16:28:28