我需要一个DizzyCreature类型的双指针(我的类(class))来指向DizzyCreature指针数组。当我运行它时,我得到“访问冲突读取位置0x ...”。我可以制作一个DizzyCreature *并很好地调用其成员函数,但是当无法运行该数组并对每个obj执行相同的操作时。

我正在遵循以下指示:
http://www.cplusplus.com/forum/beginner/10377/



Server.h:

class Server
{
 public:
  Server(int x, int y, int count);
  ~Server(void);

  void tick();


 private:
  DizzyCreature** dcArrPtr;
  DizzyCreature* dcPtr;

  int _count;
};

Server.cpp:
Server::Server(int x, int y, int count)
{
  dcPtr = new DizzyCreature[count];       // this works just fine

  dcArrPtr = new DizzyCreature*[count];   // this doesn't (but gets past this line)
  _count = count;
}

Server::~Server(void)
{
  delete[] *dcArrPtr;
  delete[] dcPtr;
}

void Server::tick()
{
  dcPtr->takeTurn();                // just fine

  for (int i = 0; i < _count; i++) {
    dcArrPtr[i]->takeTurn();        // crash and burn
  }
}

编辑:
成员函数takeTurn()在DizzyCreature的父类中。该程序将其放入函数中,但是一旦尝试更改私有(private)成员变量,就会引发异常。如果重要的话,DizzyCreature的类型为GameCreature和WhirlyB,因为这是MI上的任务。

最佳答案

您已经为dcArrPtr分配了空间,但是没有分配此数组中的每个对象。您必须执行以下操作:

Server::Server(int x, int y, int count)
{
  dcPtr = new DizzyCreature[count];

  dcArrPtr = new DizzyCreature*[count];
  for ( int i = 0; i < count; i++ ) {
    dcArrPtr[ i ] = new DizzyCreature;
  }
  _count = count;
}

Server::~Server(void)
{
  for ( int i = 0; i < count; i++ ) {
    delete dcArrPtr[ i ];
  }
  delete[] *dcArrPtr;
  delete[] dcPtr;
}

10-02 04:52