带有参数C++的void函数指针的矢量
Vector of void function pointers with parameters C++
我正在创建一个应用程序,该应用程序的类具有许多动画方法。我需要以随机的方式调用这些动画方法。所以,我的想法是创建一个void函数指针的向量,并遍历该向量。不过我无法编译它。我得到错误:"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 expression
是因为您试图存储circleAnimation01
函数调用的结果,即void
,而不是指向在接收到int和float时返回void的函数的指针。
此外,正如Quentin所说,你需要它们是函数,而不是成员函数,要么更改向量的签名,要么将这些成员更改为自由函数。
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址