我正在创建一个具有多个动画方法的类的应用程序.我需要以随机的方式调用这些动画方法.所以,我的想法是创建一个void函数指针的向量,并遍历向量.我不能让它编译.我收到了错误:"invalid use of void expression".
适用代码:
.H
std::vector<void(*)(int,float)> animationsVector;
void setAnimations();
void circleAnimation01(int circleGroup, float time);
Run Code Online (Sandbox Code Playgroud)
的.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
}
Run Code Online (Sandbox Code Playgroud)
我已经关注了其他一些帖子,这些帖子表明我做得对,但它仍然无法编译,我不知道为什么.
polygonCluster01::circleAnimation01不是一个独立的功能,而是一个成员功能.因此,您需要一个成员函数指针来存储其地址.这是您正在寻找的类型:
std::vector<void(polygonCluster01::*)(int,float)> animationsVector;
// ^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
编辑:让我们完成这个答案.
当您为向量提供正确的类型时,它仍然无法编译.这是因为,如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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
383 次 |
| 最近记录: |