2013-04-05 165 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