[英]user-defined function as a parameter passed to cpp class constructor
i want to have a class member which is a pointer to undefined typical function . 我想有一个类成员,它是未定义典型函数的指针。
the function must be performed by user. 该功能必须由用户执行。 the user must pass the function as a parameter to class constructor. 用户必须将该函数作为参数传递给类构造函数。 the function is called in the scope of class methodes. 该函数在类方法的范围内调用。 can i do these tasks like this ? 我可以做这些任务吗?
class MyClss
{
private:
bool (*f)();
public:
MyClss(bool (*fp)());
void MyMethod();
}
MyClss::MyClss(bool (*fp)())
{
f = fp;
}
void MyClss::MyMethod()
{
// do tasks
if(f())
{
// do tasks
}
}
The code you have given will works fine. 您提供的代码可以正常工作。 See the code below it is the same but using std::function
from <functional>
header file. 参见下面的代码,它是相同的,但是使用<functional>
头文件中的std::function
。
#include <functional>
// The function prototype.
typedef std::function<bool()> MyFunction;
class MyClss
{
private:
MyFunction f;
public:
MyClss(MyFunction fp);
void MyMethod();
};
MyClss::MyClss(MyFunction fp)
{
f = fp;
}
void MyMethod()
{
// do tasks
if(f())
{
// do tasks
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.