C++创建一个被指向作为参数的函数
C++ Creating a function that is being pointed to as an argument
所以这很难解释,但我会尽我所能。
我有一个函数,我的一个类将函数指针作为参数,我想做的是将函数定义为参数的一部分。即:
object->setFunctionPointer({string a = ""; return a;});
这可能吗?如果是的话,正确的语法是什么?
在C++11中,你可以做到这一点。你可以使用C++lambda(匿名函数)。
请参阅上的示例代码http://ideone.com/8ZTWSU
#include <iostream>
using namespace std;
typedef const char * (*funcptr)();
funcptr s;
void setFuncPtr(funcptr t)
{
s = t;
}
int main() {
// your code goes here
setFuncPtr([]{return "Hello n"; });
printf("%sn", s());
return 0;
}
如果我们谈论C++,应该使用std::函数,而不是函数指针。除非您正在与C API接口。
class Foo{
SetFunc(std::function<void(int)> func)
{
m_func = func;
}
private:
std::function<void(int)> m_func;
};
如果函数是类的成员,则不能使用普通函数指针来存储其地址。你需要的是一名代表;它们是用于方法的专用函数指针。在互联网上搜索C++代表,你会发现很多例子。
(注意:静态方法可能有一个例外;我不记得了。)
这里有一个完整的例子。由于c++11,这就是前进的道路:
#include<functional>
#include<string>
#include<iostream>
using namespace std;
class Object
{
public:
void setFunctionPointer(function<string(void)> function)
{
m_function = function;
}
string run()
{
return m_function();
}
private:
function<string(void)> m_function;
};
int main(int argc, char**argv)
{
Object *object = new Object;
object->setFunctionPointer([]{string a = "FOO"; return a;}); // here is the function assignment
cout << object->run() << endl;
delete object;
}
运行此程序时,会将FOO
打印到stdout。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类