动态地分配对象数组

编程入门 行业动态 更新时间:2024-10-07 22:21:03
本文介绍了动态地分配对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要的类型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.

我以下说明: www.cplusplus/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; }

更多推荐

动态地分配对象数组

本文发布于:2023-11-11 08:34:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   分配   对象   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!