动态地分配对象数组 [英] Dynamically allocating array of objects

查看:136
本文介绍了动态地分配对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的类型DizzyCreature(我班)的双指针指向DizzyCreature指针数组。当我运行它,我得到访问冲突读取位置0X ......。我可以做一个DizzyCreature *并调用它的成员函数就好了,但是,当无法通过阵列运行,并做同样的事情对每个OBJ。

I need a double pointer of type DizzyCreature (my class) to point to an array of DizzyCreature pointers. When I run it I get "Access violation reading location 0x...". I can make a DizzyCreature* and call its member functions just fine, but when cannot run through the array and do the same thing for each obj.

我以下说明:
http://www.cplusplus.com/forum/beginner/10377/

code

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.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的。该方案使得它进入的功能,但只要它试图改变一个私有成员变量中的异常。如果它的事项,DizzyCreature的类型是GameCreature和WhirlyB的,因为这是对MI赋值。

The member function takeTurn() is in a parent class of DizzyCreature. The program makes it into the function, but as soon as it attempts to change a private member variable the exception is thrown. If it matters, DizzyCreature is of type GameCreature and WhirlyB as this is an assignment on MI.

推荐答案

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

You have allocated space for dcArrPtr, but didn't allocate every object in this array. You must do following:

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;
}

这篇关于动态地分配对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆