繁体   English   中英

具有参数C ++的void函数指针的向量

[英]Vector of void function pointers with parameters C++

我正在使用具有许多动画方法的类来创建应用程序。 我需要以随机方式调用这些动画方法。 因此,我的想法是创建一个空函数指针的向量,并迭代该向量。 我无法编译它。 我收到错误消息: "invalid use of void expression"

适用代码:

。H

std::vector<void(*)(int,float)> animationsVector;
void setAnimations();
void circleAnimation01(int circleGroup, float time);

的.cpp

polygonCluster01::polygonCluster01()
{
    setAnimations();
}

void polygonCluster01::setAnimations()
{
    animationsVector.push_back(circleAnimation01(1,2.0)); //error is here
}

void polygonCluster01::circleAnimation01(int circleGroup, float animLength)
{
    //other code
}

我在这里关注了其他一些帖子,这些帖子表明我做的不错,但仍然无法编译,我不确定为什么。

polygonCluster01::circleAnimation01不是独立的函数,而是成员函数。 因此,您需要一个成员函数指针来存储其地址。 这是您要查找的类型:

std::vector<void(polygonCluster01::*)(int,float)> animationsVector;
//               ^^^^^^^^^^^^^^^^^^

编辑:让我们完成这个答案。

当您给向量提供正确的类型时,它仍然不会编译。 这是因为,如crashmstr所述,函数指针和成员函数指针仅仅是-指向(成员)函数的指针。 特别是,它们无法存储参数供以后使用,您正在尝试这样做。

因此,您真正需要的不仅仅是一个(成员)函数指针,而是可以包装一个函数和一些参数以供以后调用的东西。

好吧,C ++ 11涵盖了您! 看一下std::function 这是一个类型擦除的容器,旨在完成上面编写的内容。 您可以像这样使用它:

std::vector<std::function<void(polygonCluster01*)>> animationsVector;

...

animationsVector.push_back(std::bind(
    &polygonCluster01::circleAnimation01, // Grab the member function pointer
    std::placeholders::_1, // Don't give a caller for now
    1, 2.0 // Here are the arguments for the later call
));

...

animationsVector[0](this); // Call the function upon ourselves

向量包含函数指针,而不是您在其中调用函数的结果。

animationsVector.push_back(circleAnimation01(1,2.0));

改用这个

animationsVector.push_back(circleAnimation01);

您得到invalid use of void expressioninvalid use of void expression是因为您试图存储circleAnimation01函数调用的结果,该结果为void而不是指向在接收到int和float时返回void的函数的指针。

同样,正如Quentin所说,您需要将它们作为函数,而不是成员函数,或者更改向量的签名,或者将那些成员更改为自由函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM