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 循环之前,我会得到无意义的结果。帮助将不胜感激,谢谢...抱歉格式很糟糕。

4

1 回答 1

2
 myObject[i] = objectPointer;

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

于 2013-04-05T16:16:18.000 回答