c ++动态2d数组不使用默认构造函数

时间:2013-05-07 20:32:29

标签: c++ arrays dynamic constructor default

我遇到了一个超出我所知的问题。我正在研究一个HGE项目,但这是一个c ++问题,而不是HGE引擎本身。

问题: 我想在5个不同的乌龟上创建一个包含3种不同动画的2D数组。但是,我需要在HGE中使用这样的构造函数; turtleAnim [i] =新的hgeAnimation(turtleTexture,6,6,0,0,110,78)

但我不知道怎么做! interwebz上的所有示例都处理问题,就像它有一个默认构造函数一样。像这样:

课堂上的

#define     TURTLECOUNT     5
#define     TURTLEANIMATIONS    3

private:
hgeAnimation** turtleAnim;

在the.cpp

turtleAnim= new hgeAnimation*[TURTLECOUNT];

for(int i=0; i<TURTLECOUNT; i++)
{
    turtleAnim[i]= new hgeAnimation[TURTLEANIMATIONS]; // Uses default constructor. I don't want that cuz it doesn't exists.
    turtleAnim[i]->Play();
}

1 个答案:

答案 0 :(得分:1)

首先,您必须决定是将对象放在堆栈还是堆上。由于它们是对象,你可能想要它们在堆上,这意味着你的2D数组将有3颗星,你将访问这样的动画:

hgAnimation* theSecondAnimOnTheFourthTurtle = turtleAnim[4][2];
theSecondAnimOnTheFourthTurtle->DoSomething();

如果那就是你想要的,那么首先你要制作指针矩阵。

hgeAnimation*** turtleAnim = new hgeAnimation**[TURTLECOUNT];

然后你可以穿过乌龟。对于每只乌龟,您可以制作一系列指向动画的指针。对于该数组的每个元素,您可以自己制作动画。

for (int turt=0; turt<TURTLECOUNT; ++turt) {
   turtleAnim[turt] = new hgeAnimation*[TURTLEANIMATIONS];
   for (int ani=0; ani<TURTLEANIMATIONS; ++ani) {
      turtleAnim[turt][ani] = new hgeAnimation(parameter1, par2, par3);
   }
}

如果这看起来很棘手,删除所有阵列也会很痛苦:

for (int turt=0; turt<TURTLECOUNT; ++turt) {
   for (int ani=0; ani<TURTLEANIMATIONS; ++ani) {
      delete turtleAnim[turt][ani];
   }
   delete[] turtleAnim[turt];
}
delete[] turtleAnim;

事实上这很棘手,这是一个很好的迹象,表明可能有一种更简单的方法来设计它。

有一个像以下成员的海龟类怎么样?

class ATurtle {
  private:
    std::vector<hgeAnimation*>   myAnimations;

然后在你班级的构造函数中,你可以随心所欲地制作动画。

ATurtle::ATurtle(par1, par2, par3) {
    myAnimations.push_back( new hgeAnimation(par1, x, y) );
    myAnimations.push_back( new hgeAnimation(par2, z, a) );
    myAnimations.push_back( new hgeAnimation(par3, b, c) );
}

这样,你可以把你的海龟放在一个阵列中:

ATurtle* turtles[TURTLECOUNT];
for (int t=0; t<TURTLECOUNT; ++t) {
    turtles[t] = new ATurtle(par1, par2);
}

在你的乌龟课上,你会像这样访问动画:

(*(myAnimations.at(1)))->DoSomething();

std::vector<hgAnimation*>::iterator i, end=myAnimations.end();
for (i=myAnimations.begin(); i!=end; ++i) {
    (*i)->DoSomething();
}

但是,在这种情况下,你仍然需要在向量的每个元素上调用delete,因为你为每个元素调用了new。

ATurtle::~ATurtle() {
   std::vector<hgAnimation*>::iterator i, end=myAnimations.end();
   for (i=myAnimations.begin(); i!=end; ++i) {
       delete (*i);
   }       
}
相关问题