对象的动态内存分配

时间:2013-04-05 16:13:02

标签: c++

  #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 个答案:

答案 0 :(得分:2)

 myObject[i] = objectPointer;

它应该在循环内部,因为您在指针数组中存储了一个新引用。如果它在循环之外,那么所有指针数组都指向相同的引用。在这种情况下,在释放时应该小心,因为所有指针数组都指向相同的内存位置。