c++ - 这段代码是否遵循递归的定义?

标签 c++ recursion

我有一段代码,我怀疑它是否是递归定义的实现。我的理解是代码必须调用自身,即完全相同的函数。我还质疑以这种方式编写代码是否会增加额外的开销,这可以通过使用递归看到。你有什么想法?

class dhObject
{
public:
   dhObject** children;
   int numChildren;
   GLdouble linkLength; //ai 
   GLdouble theta; //angle of rot about the z axis
   GLdouble twist; //about the x axis
   GLdouble displacement; // displacement from the end point of prev along z
   GLdouble thetaMax;
   GLdouble thetaMin;
   GLdouble thetaInc;
   GLdouble direction;

   dhObject(ifstream &fin)
   {
      fin >> numChildren >> linkLength >> theta >> twist >> displacement >> thetaMax >> thetaMin;
      //std::cout << numChildren << std::endl;
      direction = 1;
      thetaInc = 1.0;
      if (numChildren > 0)
      {
         children = new dhObject*[numChildren];
         for(int i = 0; i < numChildren; ++i)
         {
            children[i] = new dhObject(fin);
         }
      }
   }

   void traverse(void)
   {
      glPushMatrix();
      //draw move initial and draw
      transform();
      draw();
      //draw children
      for(int i = 0; i < numChildren; ++i)
      {
         children[i]->traverse();
      }
      glPopMatrix();
   }

   void update(void)
   {
      //Update the animation, if it has finished all animation go backwards
      if (theta <= thetaMin)
      {
         thetaInc = 1.0;
      } else if (theta >= thetaMax)
      {
         thetaInc = -1.0;
      }
      theta += thetaInc;
      //std::cout << thetaMin << " " << theta << " " << thetaMax << std::endl;
      for(int i = 0; i < numChildren; ++i)
      {
         children[i]->update();
      }
   }

   void draw(void)
   {
      glPushMatrix();
      glColor3f (0.0f,0.0f,1.0f);
      glutSolidCube(0.1);
      glPopMatrix();
   }

   void transform(void)
   {
      //Move in the correct way, R, T, T, R
      glRotatef(theta, 0, 0, 1.0);
      glTranslatef(0,0,displacement);
      glTranslatef(linkLength, 0,0);
      glRotatef(twist, 1.0,0.0,0.0);
   }
};

最佳答案

这是一个定义/挑剔的问题。在这个 C 函数中:

void traverse( tree * t ) {
    if ( t != 0 ) {
        traverse( t->right );
        traverse( t->left );
    }
}

函数是递归的吗?我会说是的,即使它是在不同的对象上调用的。所以我会说你的代码也是递归的。举一个更极端的例子:

unsigned int f( unsigned int n ) {
    if ( n = 0 ) {
       return 0; 
    }
    else {
       return f( n - 1 );   // XXX
    }
}

在 XXX 处调用函数的事情显然与最初调用的事情不同。但我想每个人都会同意这是一个递归函数。

关于c++ - 这段代码是否遵循递归的定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3060671/

相关文章:

c++ - 使用 C++ 和 WinApi 显示一个额外的无模式窗口

python - 递归函数中的返回

Python 生成器 : correct code recursing a tree

java - 使用递归回溯时耗尽堆

algorithm - 这个断词算法的时间复杂度是多少? (动态规划)

c - 递归地找到列表中的完美平方和

c++ - 如何使用 QTcpSocket 获取 Protobuf 发送的数据

C++ - 连续内存和多态性

c++ - 需要读取空格和其他字符 C++

c++ - 错误 C2533 : Constructors not allowed a return type