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