【问题标题】:A function that returns an array, but that also takes a function as parameter一个返回数组的函数,但也接受一个函数作为参数
【发布时间】:2013-10-12 19:26:29
【问题描述】:

我正在使用 SDL 开发个人游戏,我有两个数组:

float player[]={...};
float blueEnemy[]={...};

我还有一个功能:

float *moveOpposite(float *actor) {
    // Skipped content.
    return actor;
}

然后,我有一个问题:

float *collideWith(float *x, float *y, float *(f)(float *a)) {
    if ((((x[0]+x[2])>y[0])&&(x[0]<(y[0]+y[2])))&&(((x[1]+x[3])>y[1])&&(x[1]<(y[1]+y[3])))) {
        *x = *f(x);
    }
    return x;
}

忽略碰撞混乱。在我的游戏中,actors 是具有 xPos、yPos、宽度、高度、速度等的数组。前四个是强制性的。像“moveActor”或“moveOpposite”这样的函数可以任意地与所有actor一起工作。 collideWith 是这些函数之一。所以,我来解释一下:

它将第一个actor和第二个actor(它们是至少大小为4的数组)作为参数,它也将一个函数作为参数。这个参数函数也接受一个演员作为参数并返回它。在 collideWith 函数内部,在测试之后,我用参数函数的结果更新第一个参数,并返回结果。我会这样应用它:

*player=*collideWith(player,blueEnemy,*moveOpposite(player));

当我尝试编译它时,我得到一个可怕的错误:

cannot convert 'float' to 'float* (*)(float*)' for argument '3' to 'float* collideWith(float*, float*, float* (*)(float*))'|

这种将另一个函数作为参数的碰撞函数对我的引擎来说非常重要。

【问题讨论】:

  • 你能切换到 C++11(例如通过更新编译器)并使用 std::function 和匿名 lambda 函数吗?
  • 从来没有这样做过。我只在 Python 中使用过 lambda 函数。有一天我会在 C++11 中尝试它:)。感谢您的提示!

标签: c++ arrays function sdl


【解决方案1】:

您的调用需要传递一个函数,因此不是

*player=*collideWith(player,blueEnemy,*moveOpposite(player));

你可能只需要

*player=*collideWith(player,blueEnemy,&moveOpposite);

【讨论】:

  • 效果很好!我非常感谢你!真的!你可以在不完全理解指针混沌的情况下走得更远,但是在这种情况下,你意识到你需要学习它哈哈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
相关资源
最近更新 更多